我正在使用EF /知识库/工作单元,但我很难理解一些细节。在UnitOfWork内部,我创建了一个新的EF DbContext(EmmaContext),但是看看版本库里面的内容,我知道它是错误的,我如何正确地获取回购库中的上下文?也许我完全走错路了?实体框架和工作单元
这里是我的UnitOfWork:
//Interface
public interface IUnitOfWork : IDisposable
{
void Commit();
}
//Implementation
public class UnitOfWork : IUnitOfWork
{
#region Fields/Properties
private bool isDisposed = false;
public EmmaContext Context { get; set; }
#endregion
#region Constructor(s)
public UnitOfWork()
{
this.Context = new EmmaContext();
}
#endregion
#region Methods
public void Commit()
{
this.Context.SaveChanges();
}
public void Dispose()
{
if (!isDisposed)
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
isDisposed = true;
if (disposing)
{
if (this.Context != null)
this.Context.Dispose();
}
}
#endregion
}
这里是仓库:
//Interface
public interface IRepository<TEntity> where TEntity : class
{
IQueryable<TEntity> Query();
void Add(TEntity entity);
void Attach(TEntity entity);
void Delete(TEntity entity);
void Save(TEntity entity);
}
//Implementation
public abstract class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class
{
#region Fields/Properties
protected EmmaContext context;
protected DbSet<TEntity> dbSet;
#endregion
#region Constructor(s)
public RepositoryBase(IUnitOfWork unitOfWork)
{
this.context = ((UnitOfWork)unitOfWork).Context;
this.dbSet = context.Set<TEntity>();
}
#endregion
#region Methods
public void Add(TEntity entity)
{
dbSet.Add(entity);
}
public void Attach(TEntity entity)
{
dbSet.Attach(entity);
}
public void Delete(TEntity entity)
{
dbSet.Remove(entity);
}
public IQueryable<TEntity> Query()
{
return dbSet.AsQueryable();
}
public void Save(TEntity entity)
{
Attach(entity);
context.MarkModified(entity);
}
#endregion
}
这基本上是我所做的,增加了一个IUnitOfWork接口,但是就单元测试而言,你认为怎么样?你真的要单元测试你的仓库和工作单元吗? – Sam
想了一下之后,我想知道如何将实现抽象为调用代码,并仍然将上下文从IoC容器获取到回购中?你有代码示例吗?谢谢!顺便说一句 - 我刚读了你的MVC 3.0书,这本好书! – Sam
@Sam - 谢谢:) – OdeToCode