Abdul Ahmad
Abdul Ahmad

Reputation: 10019

entity framework dbset which models?

Using entity framework 6 and mvc 5, assuming I have the following models:

class Employee 
{
   public int EmployeeID { get; set; }
   public String Name { get; set; }
   public Department Department { get; set; }
}

class Department 
{
   public int DepartmentID { get; set; }
   public String DepartmentName { get; set; }
   public int FloorNumber { get; set; }
}

In my DbContext class where the DbSet goes, do I do DbSet<Employee> only or do I also have to do DbSet<Department>? Right now I'm only doing DbSet<Employee> because the way I understand it, the main model is Employee which has a complex type Department inside, so theoretically if Employee loads then Department should load passively (load as in create a table)?

Currently, I have Department as a virtual field for lazy loading because when I try to access it without the virtual attribute I get a null pointer exception.

Also, my model is a little more complex than this with multiple complex objects, do each of these need their own DbSet?

Thank you

Upvotes: 0

Views: 580

Answers (1)

DavidG
DavidG

Reputation: 119176

According to the documentation (emphasis is mine):

Type Discovery

<snip>

In the following example, there is only one DbSet property defined on the SchoolEntities class (Departments). Code First uses this property to discover and pull in any referenced types.

However, if you ever wish to manipulate lists of Employees independent from your Department, then you should include it.

Upvotes: 4

Related Questions