【问题标题】:Entity Framework Unity of Work and Repository pattern实体框架统一工作和存储库模式
【发布时间】:2013-05-29 17:05:33
【问题描述】:

我正在尝试实现 UoW 和存储库模式,但出现错误

一个实体对象不能被多个 IEntityChangeTracker 实例引用。

我知道我收到该错误是因为我有两个存储库创建了两个不同的 DBContext,但我不知道为什么会发生这种情况。

这是我的 UoW 代码

 public  class UnitOfWorkRepositoryRepository : IUnitOfWorkRepository
{
    private readonly IDatabaseFactory _databaseFactory;
    private DatabaseContext _databaseContext;

    public UnitOfWorkRepositoryRepository(IDatabaseFactory databaseFactory)
    {
        _databaseFactory = databaseFactory;
    }

    public DatabaseContext Database
    {
        get { return _databaseContext ?? (_databaseContext = _databaseFactory.GetDatabaseContext()); }
    }

    public void Save()
    {
        _databaseContext.Save();
    }


}

这里是示例存储库:

  private static readonly DatabaseFactory DatabaseFactory = new DatabaseFactory();
    private static readonly UnitOfWorkRepositoryRepository UnitOfWorkRepositoryRepository = new UnitOfWorkRepositoryRepository(DatabaseFactory);

    public User GetUserById(int id)
    {
        return UnitOfWorkRepositoryRepository.Database.Users.SingleOrDefault(u => u.UserId.Equals(id));
    }

怎么了?我应该如何实施 UoW

附言

我在这个存储库中没有收到任何错误,但是另一个太长了,这个只是作为示例。

【问题讨论】:

  • 为什么要创建上下文类的多个实例?你有什么具体原因吗?

标签: entity-framework repository-pattern unit-of-work


【解决方案1】:
【解决方案2】:

看看这个SO answer,我在其中描述了一种将 Uow 从存储库中分离出来的方法。

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多