我的倉庫看起來是這樣的:實體框架 - 知識庫和工作單元 - 我正在做這個工作嗎?
public class SqlRepository<T> : IRepository<T> where T : class
{
private ExchangeSiteContext _dbContext;
private DbSet<T> _dbSet;
#region [Constructor]
public SqlRepository(ExchangeSiteContext context)
{
_dbContext = context;
_dbSet = context.Set<T>();
}
#endregion
/// <summary>
/// Gets the DbContext of the repository
/// </summary>
public ExchangeSiteContext DbContext
{
get
{
return this._dbContext;
}
}
/// <summary>
/// Get a list of entities
/// </summary>
/// <returns>List of type T entities</returns>
public IQueryable<T> GetList()
{
return this._dbSet.AsQueryable();
}
/// <summary>
/// Get a list of entities by a predicate
/// </summary>
/// <param name="predicate">The predicate</param>
/// <returns>IQueryable of T</returns>
public IQueryable<T> GetList(Expression<Func<T, bool>> predicate)
{
return this._dbSet.Where(predicate).AsQueryable();
}
...
...
}
我的工作單位是這樣的:
public class SqlUnitOfWork : IUnitOfWork, IDisposable
{
#region [Private Variables]
private ExchangeSiteContext _dbContext;
private BicycleSellerListingRepository _bicycleSellerListingRepository;
private UserProfileRepository _userProfileRepository;
#endregion
#region [Constructor]
public SqlUnitOfWork()
{
this._dbContext = new ExchangeSiteContext();
}
#endregion
#region [Custom Repositories]
public BicycleSellerListingRepository BicycleSellerListingRepository
{
get
{
if (this._bicycleSellerListingRepository == null)
this._bicycleSellerListingRepository = new BicycleSellerListingRepository(this._dbContext);
return this._bicycleSellerListingRepository;
}
}
public UserProfileRepository UserProfileRepository
{
get
{
if (this._userProfileRepository == null)
this._userProfileRepository = new UserProfileRepository(this._dbContext);
return this._userProfileRepository;
}
}
#endregion
///
/// Generic repository
///
public SqlRepository<T> GenericRepository<T>() where T : class
{
return new SqlRepository<T>(this._dbContext);
}
public void Commit()
{
this._dbContext.SaveChanges();
}
public void Dispose()
{
this._dbContext.Dispose();
this._dbContext = null;
}
}
我的倉庫都是通用的。我的工作單元有一些自定義存儲庫,主要用於無法執行通用操作的情況。
我的問題是,這看起來不對?我以前從未創建過倉庫或工作單元。這似乎工作得很好,但我不確定我是否忽略了某些事情。
看起來不錯,但爲什麼你的SqlRepository公開暴露了DbContext?通常,存儲庫只包含CRUD方法,而公共的dbcontext屬性允許太多。 – 2013-03-15 21:46:06
好的。沒有理由,也不應該。 – Hosea146 2013-03-15 21:53:45