考慮下面簡單的例子:實體框架代碼優先與存儲庫模式和延遲加載?
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
... other employee properties ...
public virtual ICollection<Sale> Sales { get; set; }
}
public class Sale
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public DateTime DateSold { get; set; }
... other sale properties ...
public virtual Employee Employee { get; set; }
}
public class SampleContext: DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Sale> Sales { get; set; }
}
我創建一個使用上述實體框架範圍內通過ID返回員工信息庫:
public interface IRepository
{
Employee EmployeeById(int id);
}
我的問題是關於填充和返回的員工銷售。在絕大多數用例中,請求特定人員的代碼只需要特定日期的銷售。我應該如何處理? 我是否將Employee類擴展到EmployeeWithDailySales對象?
我不能在調用函數中使用延遲加載,因爲一旦從存儲庫類中返回,DbContext引用就不存在。這是否意味着我做了不正確的事情? 我對倉庫本身的想法有缺陷嗎?
當我最初填充Employee對象時,我可以預加載員工的銷售額,但在大多數情況下可能會導致許多不需要的記錄。
任何意見非常感謝。我仍然試圖清楚地理解如何正確使用這些模式和框架。