我在使用 UnitOfWork 保存数据时遇到问题。我的意思是我无法使用Controller 类中的UnitOFWork.Commit()保存数据。我的实施检查如下。
工作单位
public interface IUnitOfWork<C> : IDisposable
{
int Commit();
C GetContext { get; set; }
TransactionScope BeginTransaction();
}
工作单位
public class UnitOfWork<C> : IUnitOfWork<C> where C : DbContext
{
private bool _disposed;
private readonly C _dbContext = null;
private TransactionScope _transaction;
public UnitOfWork()
{
GetContext = _dbContext ?? Activator.CreateInstance<C>();
}
public int Commit()
{
return GetContext.SaveChanges();
}
public C GetContext
{
get;
set;
}
public TransactionScope BeginTransaction()
{
if (null != _transaction)
{
_transaction = new TransactionScope();
}
return _transaction;
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (null != _transaction)
{
_transaction.Dispose();
}
if (null != _dbContext)
{
_dbContext.Dispose();
}
}
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
现在在RepositoryBase / GenericRepository
public abstract class RepositoryBase<C, E> : IRepository<E> where E : class where C : DbContext
{
private readonly IDbSet<E> _dbSet;
protected RepositoryBase(IUnitOfWork<C> unitOfWork)
{
UnitOfWork = unitOfWork;
_dbSet = UnitOfWork.GetContext.Set<E>();
}
protected IUnitOfWork<C> UnitOfWork
{
get;
private set;
}
#region IRepository<E> Members
public void Insert(E entity)
{
_dbSet.Add(entity);
UnitOfWork.GetContext.Entry(entity).State = System.Data.EntityState.Added;
UnitOfWork.Commit();
}
[...]
当我使用UnitOfWork.Commit(); 在GenericRepository中,我能够成功保存数据。但是当我使用UnitOfWork.Commit(); 使用控制器我无法保存数据。
控制器代码
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController(IEmployeeRepository employeeRepositoty, IUnitOfWork<MyDbContext> unitOfWork)
{
UnitOfWork = unitOfWork;
this._employeeRepository = employeeRepositoty;
}
[HttpPost]
public ActionResult Create(EmployeeModel employeemodel)
{
if (ModelState.IsValid)
{
using (UnitOfWork)
{
_employeeRepository.Insert(employeemodel);
UnitOfWork.Commit(); //OR UnitOfWork.GetContext.SaveChanges();
}
return RedirectToAction("Index");
}
return View(employeemodel);
}
如果我在 Controller 中使用UnitOfWork.commit()则GenericRepository Insert 方法代码检查如下
public void Insert(E entity)
{
_dbSet.Add(entity);
UnitOfWork.GetContext.Entry(entity).State = System.Data.EntityState.Added;
}
据我了解,这是 UnitOfWork 的设计问题。请帮我解决这个问题。
IEmployee存储库
public interface IEmployeeRepository : IRepository<EmployeeModel>
{
}
public class EmployeeRepository : RepositoryBase<MyDbContext, EmployeeModel>, IEmployeeRepository
{
public EmployeeRepository(IUnitOfWork<MyDbMContext> unitOfWork)
: base(unitOfWork)
{
}
}
NinjetDI配置
kernel.Bind<IUnitOfWork<MyDbContext>>().To<UnitOfWork<MyDbContext>>();
kernel.Bind<ICountryRepository>().To<CountryRepository>();
kernel.Bind<IUserProfileRepository>().To<UserProfileRepository>();
kernel.Bind<IEmployeeRepository>().To<EmployeeRepository>();