在S / O上有很多类似的问题,但这个问题有一个我没有看到的具体问题:
这是一个MVC应用程序。我正在使用Dependancy注入(Simple Injector,虽然我认为它无关紧要),它会注入Per Web Request。
我遇到的主要问题是因为我的UoW是按照网络请求注入的,所以我无法在添加数据时失败并继续使用,这是我最近需要的。
以下代码说明:
数据层
public abstract RepositoryBase<TEntity>
{
private readonly MyDbContext _context;
//fields set from contrstuctor injection
protected RepositoryBase(MyDbContext context)
{
_context = context;
}
public IList<TEntity> GetAll()
{
return _context.Set<TEntity>().ToList();
}
public TEntity GetById(Int32 id)
{
_context.Set<TEntity>().Find(id);
}
public TEntity Insert(TEntity entity)
{
_context.Set<TEntity>().Add(entity);
}
}
public UserRepository : RepositoryBase<User>, IUserRepository
{
//constructor injection
public UserRepository(MyDbContext c) : base(c) {}
public Update(Int32 id, String name, String email, Int32 ageYears)
{
var entity = GetById(id);
entity.Name = name;
entity.Email = email;
entity.Age = ageYears;
}
public UpdateName(Int32 id, String name)
{
var entity = GetById(id);
entity.Name = name;
}
}
public AddressRepository : RepositoryBase<Address>, IAddressRepository
{
//constructor injection
public AddressRepository(MyDbContext c) : base(c) {}
public Update(Int32 id, String street, String city)
{
var entity = GetById(id);
entity.Street = street;
entity.City = city;
}
public Address GetForUser(Int32 userId)
{
return _context.Adresses.FirstOrDefault(x => x.UserId = userId);
}
}
public DocumentRepository : RepositoryBase<Document>, IDocumentRepository
{
//constructor injection
public DocumentRepository(MyDbContext c) : base(c) {}
public Update(Int32 id, String newTitle, String newContent)
{
var entity.GetById(id);
entity.Title = newTitle;
entity.Content = newContent;
}
public IList<Document> GetForUser(Int32 userId)
{
return _context.Documents.Where(x => x.UserId == userId).ToList();
}
}
public UnitOfWork : IUnitOfWork
{
private readonly MyDbContext _context;
//fields set from contrstuctor injection
public UnitOfWork(MyDbContext context)
{
_context = context;
}
public Int32 Save()
{
return _context.SaveChanges();
}
public ITransaction StartTransaction()
{
return new Transaction(_context.Database.BeginTransaction(IsolationLevel.ReadUncommitted));
}
}
public Transaction : ITransaction
{
private readonly DbContextTransaction _transaction;
public Transaction(DbContextTransaction t)
{
_transaction = t;
State = TransactionState.Open;
}
public void Dispose()
{
if (_transaction != null)
{
if (State == TransactionState.Open)
{
Rollback();
}
_transaction.Dispose();
}
}
public TransactionState State { get; private set; }
public void Commit()
{
try
{
_transaction.Commit();
State = TransactionState.Committed;
}
catch (Exception)
{
State = TransactionState.FailedCommitRolledback;
throw;
}
}
public void Rollback()
{
if (_transaction.UnderlyingTransaction.Connection != null)
{
_transaction.Rollback();
}
State = TransactionState.Rolledback;
}
}
服务层
public DocumentService : IDocumentService
{
//fields set from contrstuctor injection
private readonly IDocumentRepository _docRepo;
private readonly IUnitOfWork _unitOfWork;
public void AuthorNameChangeAddendum(Int32 userId, String newAuthorName)
{
//this works ok if error thrown
foreach(var doc in _docRepo.GetForUser(userId))
{
var addendum = $"\nAddendum: As of {DateTime.Now} the author will be known as {newAuthorName}.";
_docRepo.Update(documentId, doc.Title + "-Processed", doc.Content + addendum);
}
_unitOfWork.Save();
}
}
public UserService
{
//fields set from contrstuctor injection
private readonly IUserRepository _userRepo;
private readonly IAddressRepository _addressRepo;
private readonly IUnitOfWork _unitOfWork;
private readonly IDocumentService _documentService;
public void ChangeUser(Int32 userId, String newName, String newStreet, String newCity)
{
//this works ok if error thrown
_userRepo.UpdateName(userId, newName);
var address = _addressRepo.GetForUser(userId);
_addressRepo.Update(address.AddressId, newStreet, newCity);
_unitOfWork.Save();
}
public void ChangeUserAndProcessDocs(Int32 userId, String newName, Int32)
{
//this is ok because of transaction
using(var transaction = _unitOfWork.StartTransaction())
{
_documentService.AuthorNameChangeAddendum(userId, newName); //this function calls save() on uow
//possible exception here could leave docs with an inaccurate addendum, so transaction needed
var x = 1/0;
_userRepo.UpdateName(userId, newName);
_unitOfWork.Save();
transaction.Commit();
}
}
//THE PROBLEM:
public IList<String> AddLastNameToAll(String lastName)
{
var results = new List<String>();
foreach(var u in _userRepo.GetAll())
{
try
{
var newName = $"{lastName}, {u.Name}";
_userRepo.UpdateName(u.UserId, newName);
_unitOfWork.Save(); //throws validation exception
results.Add($"Changed name from {u.Name} to {newName}.");
}
catch(DbValidationException e)
{
results.Add($"Error adding last name to {u.Name}: {e.Message}");
//but all subsequeqnet name changes will fail because the invalid entity will be stuck in the context
}
}
return results;
}
}
您可以在UserService中看到UoW实现处理ChangeUser()
,ChangeUserAndProcessDocs()
中的潜在问题通过使用显式事务来处理。
但是在AddLastNameToAll()
中问题是,如果我有100个用户要更新而第3个用户因为名称列不长而失败而需要处理新名称,那么结果3到100都将具有相同的验证消息。解决这个问题的唯一方法是为for循环的每次传递使用一个新的UnitOf Work(DbContext),这对我的实现来说是不可能的。
我的UoW + Repo实施可防止EF泄漏到其他层,并确保其他层能够创建事务。但是,如果A服务呼叫B服务,B服务可以在A准备好之前调用Save(),这总是让人感到奇怪。范围内的交易解决了这个问题,但仍然感觉有些奇怪。
我考虑过废弃UoW模式,只是让我的所有存储库操作立即提交,但是这留下了更新两种不同的enttity类型并使第二次更新失败的空白问题,但是第一次更新成功现在没有意义(参见ChangeUserAndProcessDocs()
就是一个例子。
所以我在UserRepository UpdateName()
上创建一个特殊的UpdateNameImmediately()
函数,忽略注入的上下文并创建它自己的。
public void UpdateNameImmediately(Int32 id, String newName)
{
using(var mySingleUseContext = new MyDbContext())
{
var u = mySingleUseContext.Users.Find(id);
u.Name = newName;
mySingleUseContext.SaveChanges();
}
}
这感觉很奇怪,因为现在这个函数的行为与我的所有其他存储库操作完全不同,并且不会服从该事务。
是否有UoW + EF + Repository Pattern + DI的实现解决了这个问题?
答案 0 :(得分:1)
工作原理:
public class DbFactory : Disposable, IDbFactory
{
HomeCinemaContext dbContext;
public HomeCinemaContext Init()
{
return dbContext ?? (dbContext = new HomeCinemaContext());
}
protected override void DisposeCore()
{
if (dbContext != null)
dbContext.Dispose();
}
}
public class UnitOfWork : IUnitOfWork
{
private readonly IDbFactory dbFactory;
private HomeCinemaContext dbContext;
public UnitOfWork(IDbFactory dbFactory)
{
this.dbFactory = dbFactory;
}
public HomeCinemaContext DbContext
{
get { return dbContext ?? (dbContext = dbFactory.Init()); }
}
public void Commit()
{
DbContext.Commit();
}
}
public class EntityBaseRepository<T> : IEntityBaseRepository<T>
where T : class, IEntityBase, new()
{
private HomeCinemaContext dataContext;
#region Properties
protected IDbFactory DbFactory
{
get;
private set;
}
protected HomeCinemaContext DbContext
{
get { return dataContext ?? (dataContext = DbFactory.Init()); }
}
public EntityBaseRepository(IDbFactory dbFactory)
{
DbFactory = dbFactory;
}
#endregion
public virtual IQueryable<T> GetAll()
{
return DbContext.Set<T>();
}
public virtual IQueryable<T> All
{
get
{
return GetAll();
}
}
public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = DbContext.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public T GetSingle(int id)
{
return GetAll().FirstOrDefault(x => x.ID == id);
}
public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
{
return DbContext.Set<T>().Where(predicate);
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry<T>(entity);
DbContext.Set<T>().Add(entity);
}
public virtual void Edit(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry<T>(entity);
dbEntityEntry.State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry<T>(entity);
dbEntityEntry.State = EntityState.Deleted;
}
}
主类是DbFactory,它包含只有一个EF db context 的实例。因此,无论你在不同的存储库中做什么,应用程序总是使用一个上下文。
类EntityBaseRepository也在DbFactory提供的同一数据库上下文上运行。
UnitOfWork仅传递给控制器,以便能够使用方法Commit,在同一个db context实例上保存对数据库的所有更改。
你probalby不需要你在代码中使用的交易。
完整教程在这里:
找到单词:&#34; DbFactory&#34;或&#34; UnitOfWork&#34;详细了解。
答案 1 :(得分:0)
.firstChild
使其立即提交每个更改的解决方案是“立即存储库包装器”。这允许我重用我现有的代码,并允许我在测试我的服务时继续轻松地模拟存储库行为。用户的示例立即存储库包装器如下所示:
const clone = document.querySelector("div").cloneNode(true);
let flattenNodes = (el, not = el, res = []) => {
for (let node of el.childNodes) {
if (node.nodeName === "#text" && !node.childNodes.length) {
if (node.previousElementSibling && node.parentElement !== not) {
let tag = node.parentElement.tagName.toLowerCase();
res.push(`<${tag}>${node.textContent}</${tag}>`);
} else {
res.push(node.textContent);
}
}
if (node.nodeName !== "#text"
&& Array.from(node.childNodes).every(e => e.nodeName === "#text")) {
res.push(node.outerHTML);
} else {
if (node.tagName && node.tagName !== "#text"
&& node.firstChild.nodeName === "#text") {
let tag = node.tagName.toLowerCase();
res.push(`<${tag}>${node.firstChild.textContent}</${tag}>`);
node.firstChild.remove();
flattenNodes(node, not, res);
}
}
}
return res
}
let res = flattenNodes(clone);
document.querySelector("pre")
.textContent = res.join("");
这对于批量处理的罕见情况非常有用,我需要立即提交。