EF 4.1 Code First - 单个上下文还是多个上下文?
任何人都可以就单一上下文还是多个上下文是否是最佳实践提供任何建议吗?
例如,我应该有一个如下的单一上下文:
public class MyContext
: DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Country> Countries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CountryConfiguration());
modelBuilder.Configurations.Add(new CompanyConfiguration());
base.OnModelCreating(modelBuilder);
}
}
还是我最好为公司和国家创建一个单独的上下文?因此 ConpanyContext 和 CountryContext 都会公开一个 DbSet 属性。
这可能只是个人选择,但我们的数据库将包含数百个实体。因此,我想从一开始就解决这个问题。
非常感谢,
保罗。
Could anyone offer any advice on whether it is best practice to have a single context or multiple contexts?
For example, should I have a single context as follows:
public class MyContext
: DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Country> Countries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CountryConfiguration());
modelBuilder.Configurations.Add(new CompanyConfiguration());
base.OnModelCreating(modelBuilder);
}
}
Or would I be better creating a separate context for Companies and Countries? So ConpanyContext and CountryContext which would both expose a single DbSet property.
It may just be personal choice, but our database is going to consist of 100s of entities. I'd therefore like to get this right to begin with.
Many thanks,
Paul.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个简单的经验法则:一个模式/域,一个上下文。
A simple rule of thumb: one schema/domain, one context.
如果可能的话,尝试将它们沿着有意义的线分开。
一个上下文中的 100 个实体可能看起来很糟糕,但想想你的替代方案,100 个不同的上下文?
然后你必须做类似的事情,
如果你需要查询多个表,你就会有嵌套的上下文,这会变得很难看。
你会开始遇到这样的事情:
我无法想象这样会提高性能,但我确信维护会很痛苦。
If at all possible, try and split them along meaningful lines.
100 entities in a context might seem bad, but think of your alternative, 100 different contexts?
Then you'd have to do things like
If you needed to query multiple tables you'd have nested contexts and it would get ugly.
You'd start having things like
I can't imagine performance would be improved going that way, but I'm sure maintenance would be a pain.