Object depending on another object - when to load

2019-09-05 21:13发布

Imagine a class of employee:

public class Employee
 {
   public int ID { get; set; }
   public string FirstName { get; set; }
   public Employee(int ID, string FirstName)
       {
         this.ID = ID;
         this.FirstName = FirstName;
       }
 }

The data for the employee is loaded in from a data access layer (DAL), which is another seperate class.

Later I decide that I need another property namely a Department for the employee, however the department is a huge category on its own as it has its own properties. So I end up making a class for it:

class Department
 {
  public string DepartmentID { get; set;}
  public string CostCenter { get; set; }
  public bool hasManager { get; set; }
  //more code
  //constructor for department
 }

So I then change my employee class from above to include an instance of a department:

public class Employee {
  //existing code for an employee above PLUS the below
  public Department d { get; set; }
}

So now I'm good I have an employee class with a department associated with it. When I call my DAL class to get the data for my employee this can return the actual department in the SQL query. So I can assign the DepartmentID of the class Department easily. But when / how should I assign all the other properties of the Department class.

In addition, the properties for CostCenter, hasManager, etc are all stored in the database layer. If I originally only am getting back the DepartmentID should I call the DAL class again to get all the relevant information for the department? If so where should I call that, I didnt think calling the DAL class from my department constructor was a good idea. I know I could just create a relationship between my two tables and get relevant information from the department and then I can instantiate my department within the employee constructor. But the employee class has a LOT of properties already lots of fields coming back from the database, so if I did this my constructor may become larger and larger....

1条回答
该账号已被封号
2楼-- · 2019-09-05 22:01

Well, you have choices to make...

I assume you have your own DAL beacuse EF and Linq2Sql have built-in options for this.

  1. Eager loading - load the Department with the Person.
  2. On demand loading: if (p.d == null) ...
  3. Lazy loading: do the on-demand inside the getter of the d property.
查看更多
登录 后发表回答