我正在使用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