简体   繁体   English

EF最佳实践:使用导航集合与DBSet

[英]EF Best Practices: Using Navigation collection vs DBSet

Consider this EF code-first schema: 考虑以下EF代码优先模式:

class Organization
{
   public int ID { get; set; }
   public ICollection<Employee> Employees { get; set; }
}
class Employee
{
   public int ID { get; set; }
   public Organization Employer { get; set; }
}
class MyDbContext: DbContext
{
   public DBSet<Employee> Employees { get; set; }
   public DBSet<Organization> Organizations  { get; set; }
}

Let's say we have one instance of Organization, and want to add a new employee. 假设我们有一个Organization实例,并且想要添加一个新员工。 We can do (A) 我们可以做(A)

organization.Employees.Add(new_guy); 

or (B) 或(B)

new_guy.Organization = organization;
dbContext.Employees.Add(new_guy);

Let's say one part of the code uses organization.Employees.Add. 假设代码的一部分使用了organization.Employees.Add。 A different part of the code references dbContext.Employees. 代码的另一部分引用dbContext.Employees。 Then dbContext.Employees will not yet contain new_guy, as the two collections are not magically synced with each other. 然后,dbContext.Employees将不再包含new_guy,因为这两个集合没有相互魔术地同步。

This can be very problematic when different team members use (A) or (B). 当不同的团队成员使用(A)或(B)时,这可能会很成问题。

What's the best practice here? 这里的最佳做法是什么? Should we always access DbSet and never use navigation properties? 我们应该始终访问DbSet而不使用导航属性吗? Should we write a custom wrapper? 我们应该编写一个自定义包装器吗?

If I understand well, your problem is probably the lifetime of your DbContext . 据我了解,您的问题可能是DbContext的生存期。 If you are using a DI Framework, you typically configure the lifetime of this object per request. 如果使用的是DI框架,则通常会按请求配置此对象的生存期。

With Castle Windsor, this will look like this: 使用温莎城堡,情况将如下所示:

container.Register(
         Component.For<DbContext>()
        .ImplementedBy<MyDbContext>()
        .LifestylePerWebRequest());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM