实体框架4.1通用存储库

时间:2011-10-04 10:34:41

标签: c# asp.net entity-framework entity-framework-4.1 repository-pattern

使用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());

如果我不必每次都启动一个新的存储库,我更喜欢它。有没有办法可以创建存储库然后使用泛型方法? E.g:

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);

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

2 个答案:

答案 0 :(得分:1)

只是为了澄清:您是否正在尝试创建一个可以由多个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.
}

挂起我的意思是更改尚未保存到数据库中。

答案 1 :(得分:1)

拥有此类存储库将违反Single responsibility principle。单一存储库应该只负责管理单一类型的实体。

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

相关问题