我正在尝试实现 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/