1

考慮下面簡單的例子:實體框架代碼優先與存儲庫模式和延遲加載?

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對象時,我可以預加載員工的銷售額,但在大多數情況下可能會導致許多不需要的記錄。

任何意見非常感謝。我仍然試圖清楚地理解如何正確使用這些模式和框架。

回答

1

首先我建議你使用session-per-request模式來處理DbContext。

在Application_BeginRequest方法中實例化DbContext並允許從控制器訪問它。

在Application_EndRequest中處理/關閉您的DbContext。

然後,我認爲「請求某人只需要某一天的銷售」是您必須投入服務的商業規則。

因此,添加像EmployeeService這樣的服務來管理您的Employee類。添加方法類似

員工GetByDate(DateTime的salesDay)

在這裏裝載的員工和銷售數據對於給定的日期。

您必須在EmployeeService中注入DbContext。