[英]Entity Framework - Repository and Unit of Work - Am I doing this right?
我的存儲庫如下所示:
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;
}
}
我的存儲庫都是通用的。 我的工作單元有一些自定義存儲庫,主要用於無法執行一般操作的情況。
我的問題是,這看起來正確嗎? 我以前從未創建過存儲庫或工作單元。 這似乎工作得很好,但是我不確定是否忽略了某些內容。
沒有唯一正確的存儲庫和UoW實現(就我而言,我更喜歡UoW是傳遞給存儲庫的DbContext而不是DbContext的簡單包裝)。 但是我在您的實現中看到了一些問題:
GetList
方法令人困惑。 他們正在返回IQueryable
而不是列表。 我認為GetAll
是更合適的名稱。 _dbSet.AsQueryable()
,因為DbSet<T>
實現了IQueryable<T>
。 只需返回_dbSet
。 DbContext
。 DbContext
? _dbContext
,無需將_dbContext
設置為null。 在開發人員世界中,工作單元和存儲庫模式的實現仍然是一個激烈的辯論主題,盡管如此,我在閱讀了很多相關知識之后,可以為您提供一些我收集的指導原則:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.