entity-framework - Entity Framework 工作统一和存储库模式

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

我正在尝试实现 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 - Entity Framework 工作统一和存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16819958/

相关文章:

entity-framework - 要刷新的对象集合中索引 0 处的元素具有 null EntityKey 属性值或未附加到此 ObjectStateManager

ninject - 寻找行为类似于 InRequestScope 的 Ninject 范围

c# - 多话多对多在添加 child 时不更新数据库

database - 在 SQL Azure 上使用 EF6 MainContextDropInitializer 时超时

entity-framework - 如何检查迁移中是否存在表?

c# - 在 Entity Framework 中合并

entity-framework - 无法检查 Entity Framework CTP5 模型兼容性,因为数据库不包含模型元数据

c# - Controller 注入(inject)服务类依赖关系还是留给服务来解决它自己的依赖关系?什么是首选方式

c# - ASP.net Web 表单在哪里使用 UnitOfWork 模式处理实体上下文

model-view-controller - 存储库模式 + 工作单元