问题
I'm new to EF4, and I'm trying to figure out the best way to create my DbContext class(es).
Is there any problem (specially performance) in putting all my tables / entities into one and only one DbContext class, like the code below?
public class AllInOneDb : DbContext
{
public DbSet<Customer> Customers{ get; set; }
public DbSet<Address> Addresses{ get; set; }
public DbSet<Order> Order{ get; set; }
public DbSet<Product> Products{ get; set; }
public DbSet<Category> Categories{ get; set; }
// and more and more entities...
}
Or should I model my classes based on the subsets of functionalities?
public class CustomerDb : DbContext
{
public DbSet<Customer> Customers{ get; set; }
public DbSet<Address> Addresses{ get; set; }
public DbSet<Order> Order{ get; set; }
}
public class ProductDb : DbContext
{
public DbSet<Product> Products{ get; set; }
public DbSet<Category> Categories{ get; set; }
public DbSet<Order> Order{ get; set; } // look Order entity again!
}
Thanks
回答1:
If you have sub areas which have specific business logic, you can split it into multiple DbContext
. (These smaller contexts follow a pattern critical to Domain Driven Design
called Bounded Contexts). There are a number of benefits to creating DbContexts that are targeted to these various processes rather than one all-purpose
context. As your application grow, it will be much easier to maintain each context as well as locate the logic you need within it. (Better than adding or modifying existing logic in single DbContext
with many DbSet
properties and fluent configuration for many class)
Performance is another consideration. When Entity Framework creates an in-memory model of the context, the larger the context is the more resources are expended to generate and maintain that in-memory model.
If you are going to share instances(Order
) between multiple contexts, Entity can only be attached to one context at a time. Detach Order from the Customer DbContext first and attach Order to a Product DbContext. And you should be careful about (or just avoid) moving Added, Modified, or Deleted entities from one context to another.
Order order;
using (var custDb = new CustomerDb()){
order = custDb.FirstOrDefault(o=>OrderId == "orderid");
}
using (var prodDB = new ProductDb()){
prodDB.Attach(order);
...
}
来源:https://stackoverflow.com/questions/10150383/should-efs-dbcontext-contains-all-tables