【问题标题】:How to write generic innerJoin in Generic Repository?如何在通用存储库中编写通用内部联接?
【发布时间】:2012-02-26 22:25:51
【问题描述】:

我正在使用通用存储库来开发我自己的带有实体框架的 BLL。Generic Repository 但是所有通用存储库都没有内部连接。乐在下面:

 public interface IRepository
{
    IQueryable<T> List<T>() where T : class;
    T Get<T>(int id) where T : class;
    void Create<T>(T entityTOCreate) where T : class;
    void Edit<T>(T entityToEdit) where T : class;
    void Delete<T>(T entityToDelete) where T : class;
}

如何将上述代码转换为:

 public interface IRepository
{
    IQueryable<T> List<T>() where T : class;
    T Get<T>(int id) where T : class;
    void Create<T>(T entityTOCreate) where T : class;
    void Edit<T>(T entityToEdit) where T : class;
    void Delete<T>(T entityToDelete) where T : class;
void InnerJoin<T>(T entityName, TNew entityName2) where T : class, where TNew : class;
}

或者我认为我们可以像这样使用 Fluent 界面模式:

    public List<MyWorker> ListByID( int ID)
{
    using (var Ctx = new DomainRepository<Worker>(new ProposalsEntities()))
         return Ctx.Find<Worker>(q => q.ID== ID).ToList().InnerJoin(XEntity,x=>x.ID=q.ID).InnerJoin(YEntity,y=>y.ID=q.ID);
}

Yuo 可以给出另一个建议来解决这个奇妙的问题。我如何在通用存储库中编写以上加入代码?

【问题讨论】:

标签: c# .net design-patterns c#-4.0 fluent-interface


【解决方案1】:

这对于您的通用存储库是不可能的。将数据库的关系模型抽象到太多不是一个好主意。它会阻止您使用特定于数据库的功能,例如 ... 连接。

您可以通过添加附加方法来修复您的存储库:

IQueryable<T> Query<T>() { return dataContext.GetTable<T>(); }

(此示例适用于 Linq 2 Sql)。

您需要能够为 callerd 提供可组合的查询,而不是列表。然后调用者可以写:

from w in repo.Query<Worker>()
join e in repo.Query<XEntity>() on ...

如果允许评论:通用存储库模式不是一个好主意。它帮助不大,却造成很大的伤害。

要么直接使用DataContext/EntityContext/Session,要么使用专门的存储库。

【讨论】:

  • 我们可以用字符串值做到这一点吗: void InnerJoin(T entityName, string entityName2) where T : class
【解决方案2】:

存储库不应公开联接功能。存储库提供的域对象可能由保存在多个表中的数据组成,但域层不应该知道这一事实,或者更一般地说,数据在持久层中采用的格式。某些数据源甚至可能无法提供连接功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-13
    • 2023-03-03
    • 2021-11-16
    • 2014-09-08
    • 1970-01-01
    • 2021-09-15
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多