首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为每个对象创建通用存储库与特定存储库的优势?

为每个对象创建通用存储库与特定存储库的优势?
EN

Stack Overflow用户
提问于 2009-08-05 00:18:19
回答 5查看 33.6K关注 0票数 134

我们正在开发一个ASP.NET MVC应用程序,现在正在构建存储库/服务类。我想知道,创建一个所有存储库都实现的通用IRepository接口与每个存储库都有自己独特的接口和方法集相比,有没有什么主要优势。

例如:一个通用的IRepository接口可能类似于(取自this answer):

代码语言:javascript
复制
public interface IRepository : IDisposable
{
    T[] GetAll<T>();
    T[] GetAll<T>(Expression<Func<T, bool>> filter);
    T GetSingle<T>(Expression<Func<T, bool>> filter);
    T GetSingle<T>(Expression<Func<T, bool>> filter, List<Expression<Func<T, object>>> subSelectors);
    void Delete<T>(T entity);
    void Add<T>(T entity);
    int SaveChanges();
    DbTransaction BeginTransaction();
}

每个存储库都将实现此接口,例如:

  • CustomerRepository:IRepository
  • ProductRepository:IRepository
  • etc.

我们在以前的项目中遵循的备选方案是:

代码语言:javascript
复制
public interface IInvoiceRepository : IDisposable
{
    EntityCollection<InvoiceEntity> GetAllInvoices(int accountId);
    EntityCollection<InvoiceEntity> GetAllInvoices(DateTime theDate);
    InvoiceEntity GetSingleInvoice(int id, bool doFetchRelated);
    InvoiceEntity GetSingleInvoice(DateTime invoiceDate, int accountId); //unique
    InvoiceEntity CreateInvoice();
    InvoiceLineEntity CreateInvoiceLine();
    void SaveChanges(InvoiceEntity); //handles inserts or updates
    void DeleteInvoice(InvoiceEntity);
    void DeleteInvoiceLine(InvoiceLineEntity);
}

在第二种情况下,表达式(LINQ或其他)将完全包含在存储库实现中,任何实现服务的人只需要知道要调用哪个存储库函数。

我想我看不到在服务类中编写所有表达式语法并将其传递给存储库的好处。这不是意味着在许多情况下,易于使用的LINQ代码正在被复制吗?

例如,在我们的旧发票系统中,我们调用

代码语言:javascript
复制
InvoiceRepository.GetSingleInvoice(DateTime invoiceDate, int accountId)

来自一些不同的服务(客户、发票、账户等)。这似乎比在多个地方编写以下代码要干净得多:

代码语言:javascript
复制
rep.GetSingle(x => x.AccountId = someId && x.InvoiceDate = someDate.Date);

我看到使用特定方法的唯一缺点是,我们最终可能会得到许多Get*函数的排列,但这似乎仍然比将表达式逻辑推入服务类更可取。

我遗漏了什么?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1230571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档