【发布时间】:2014-02-15 15:12:46
【问题描述】:
我计划在我的实体框架项目中使用通用存储库。但是对于基本通用存储库不包含的操作,哪个更好地扩展存储库。
继承:
public class CustomerRepository:Repository<Customer>
{
public decimal GetCustomerOrderTotalByYear(int customerId, int year)
{
return base
.FindById(customerId)
.Orders.SelectMany(o => o.OrderDetails)
.Select(o => o.Quantity*o.UnitPrice).Sum();
}
}
扩展方法:
public static class CustomerRepositoryExtensions
{
public static decimal GetCustomerOrderTotalByYear(this Repository<Customer> customerRepository, int customerId, int year)
{
return customerRepository
.FindById(customerId)
.Orders.SelectMany(o => o.OrderDetails)
.Select(o => o.Quantity*o.UnitPrice).Sum();
}
}
【问题讨论】:
-
我赞成继承方法,因为查询特定于 CustomerRepository 类。一个问题。为什么 CustomerRepository 类是静态的?
-
又是扩展风格;它也特定于 Repository
。而且我把第一堂课的static去掉了,写错了。 -
扩展方法的问题是,您需要在计划使用扩展方法的任何地方包含命名空间。使用继承方法,您可以使用存储库对象免费访问该方法。
-
当通用实现也无法满足您的所有需求时,创建一个具体的存储库是完全可以的。但是,我会使用扩展方法的唯一时间是当您无法控制“服务”的实现时。目前,我完全有这种情况——提供的版本具有抽象属性,我无法看到“幕后”(还)。所以,是的……去做吧。
标签: c# entity-framework inheritance extension-methods repository-pattern