繁体   English   中英

实体框架4.1通用存储库

[英]Entity Framework 4.1 generic repository

使用Entity Framework 4.1并尝试创建上面的存储库层作为测试。 基本上,我正在玩它以变得熟悉,因为我是Entity Framework和存储库模式的新手。 我遵循了一些教程,并创建了一个通用存储库。 像这样启动存储库:

CentralDataRepositoryEntities CentralDataRepositoryEntities = new CentralDataRepositoryEntities();

Repository<Group> Rep = new Repository<Group>(CentralDataRepositoryEntities);
IEnumerable<Group> Groups = Rep.Get<Group>(g => g.JorMGroupId == 114);

Console.WriteLine(Group.Single());

Repository<Job> Rep1 = new Repository<Job>(CentralDataRepositoryEntities);
IEnumerable<Job> Jobs = Rep1.Get<Job>(j => j.jobId == 2138);

Console.WriteLine(Job.Single());

如果我不必每次都启动一个新的存储库,则最好使用它。 有没有一种方法可以创建存储库,然后改用通用方法? 例如:

Repository Rep = new Repository(CentralDataRepositoryEntities);
IEnumerable<Group> Groups = Rep.Get<Group>(g => g.JorMGroupId == 114);
IEnumerable<Job> Jobs = Rep.Get<Job>(j => j.jobId == 2138);

这是一个好主意吗? 为什么要为每种类型创建一个单独的存储库?创建多个存储库对性能有何影响?

只是为了澄清一下:您是否要建立一个可由多个ORM使用的“通用”存储库,还是仅用于EF? 如果是后者,则已经浪费了时间,因为已经实施了这种模式。 DbContext是您所谓的“工作单元”,它公开的Set方法是为特定类型创建Repository

一个例子:

using(var ctx = new MyContext()) // Unit of Work
{
    var userRepository = ctx.Set<User>(); // Creates user repository
    var logRepository = ctx.Set<Log>(); // Creates log repository
    userRepository.Add(newUser); // Adds a "pending" item to the userRepository
    logRepositor.Add(logMsg); // Adds a "pending" item to the logRepository

    ctx.SaveChanges(); // Adds the "pending" items all at once.
}

待定是指更改尚未保存到数据库。

拥有这样的存储库将违反单一责任原则 单一存储库应仅负责管理单一类型的实体。

此通用存储库模式仅适用于简单方案。 在某些情况下,您将需要存储库中用于特定实体的其他方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM