Open棟梁Project - マイクロソフト系技術情報 Wiki
例えば、ProductContext?クラスは
public class ProductContext : DbContext { public DbSet<Category> Categories { get; set; }
メモリのデータ保持は、DbContext?オブジェクト インスタンスのライフタイムと同じ。
以下のように、usingを使うと、ライフタイムは明確になる。
using (ProductContext context = new ProductContext()) { // Perform data access using the context }
using (ProductContext context = new ProductContext()) { // Below code is enumerated using ToList() method. // Stores all records in “myCategories” object (Memory) IList<Category> myCategories = context.Database.SqlQuery<Category>("Select * from Category").ToList(); }
TransactionScopeを使用してトランザクションを処理する。
using (EntitiesContext context = new EntitiesContext()) { using (TransactionScope scope = new TransactionScope()) { //Code here } }
ASP.NET MVCでDbContext?のトランザクションと
独自SQL 処理のトランザクションを同一のスコープにする
http://blog.makotoishida.com/2012/12/aspnet-mvcdbcontextsql.html
トランザクションを維持するために、2つの新しいAPIを導入している。
using (EntitiesContext context = new EntitiesContext()) { using (var transaction = context.Database.BeginTransaction()) { try { EmployeeMaster employee = new EmployeeMaster(); employee.Code = "A0001"; employee.Name = "Jignesh Trivedi"; employee.DepartmentId = 1; context.Employees.Add(employee); context.SaveChanges(); DepartmentMaster dept = new DepartmentMaster(); dept.Code = "DEP0001"; dept.Name = "Department 1"; context.Departments.Add(dept); context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); } } }
using (SqlConnection con = new SqlConnection("connectionString")) { con.Open(); using (var transaction = con.BeginTransaction()) { // Do something.... //Pass this transaction to Entity Framework.... using (EntitiesContext context = new EntitiesContext(con, false)) { context.Database.UseTransaction(transaction); EmployeeMaster employee = new EmployeeMaster(); employee.Code = "A0001"; employee.Name = "Jignesh Trivedi"; employee.DepartmentId = 1; context.Employees.Add(employee); context.SaveChanges(); } } }
((IObjectContextAdapter)context).ObjectContext.Detach(myCategory);
ObjectContext context = ((IObjectContextAdapter)myDbContext).ObjectContext; // Refresh specific Entity object in the context context.Refresh(System.Data.Objects.RefreshMode.StoreWins, myCategory);
(OR)
// Refresh All Entities in the context. var refreshableObjects = myDbContext.ChangeTracker.Entries().Select(c => c.Entity).ToList(); context.Refresh(System.Data.Objects.RefreshMode.StoreWins, refreshableObjects);
データベースに、50~100のテーブルが含まれている場合、
すべてのエンティティを含む1つの大きなEntity Dataモデルを持つことは良い方法ではない。
エンティティを1つの大きいEntity Dataモデルに集約すると、下記のようないくつかの問題を起こす。
上記を回避するため、
ベスト・プラクティスは任意の単位にEntity Dataモデルを分割する方法である。
https://github.com/OpenTouryoProject/SampleProgram/issues/3