我正在使用通用存储库通过 Entity Framework 开发我自己的 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 可以给出另一个建议来解决这个奇妙的问题。我如何在通用存储库中编写上面的连接代码?
请您参考如下方法:
这对于您的通用存储库是不可能的。将数据库的关系模型抽象得太多并不是一个好主意。它会阻止您使用特定于数据库的功能,例如...联接。
您可以通过添加附加方法来修复您的存储库:
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 或使用专门的存储库。
