【发布时间】:2012-01-20 14:13:22
【问题描述】:
考虑以下简单示例:
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 对象时预加载员工的销售额,但在大多数情况下这可能会导致许多不需要的记录。
非常感谢任何建议。我仍在尝试清楚地了解如何正确使用这些模式和框架。
【问题讨论】:
标签: asp.net-mvc-3 entity-framework design-patterns ef-code-first repository-pattern