简体   繁体   中英

EF Best Practices: Using Navigation collection vs DBSet

Consider this EF code-first schema:

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. We can do (A)

organization.Employees.Add(new_guy); 

or (B)

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

Let's say one part of the code uses organization.Employees.Add. A different part of the code references dbContext.Employees. Then dbContext.Employees will not yet contain new_guy, as the two collections are not magically synced with each other.

This can be very problematic when different team members use (A) or (B).

What's the best practice here? Should we always access DbSet and never use navigation properties? Should we write a custom wrapper?

If I understand well, your problem is probably the lifetime of your DbContext . If you are using a DI Framework, you typically configure the lifetime of this object per request.

With Castle Windsor, this will look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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