实体框架-存储库和工作单元-我这样做对吗?
本文关键字:这样做 单元 工作 框架 存储 实体 | 更新日期: 2023-09-27 18:04:03
我的存储库是这样的:
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的简单包装器,它传递给存储库)。但这里有一些问题,我看到在你的实现:
-
GetList
方法令人困惑。它们返回的是IQueryable
而不是list。我觉得GetAll
这个名字更合适。 - 不需要调用
_dbSet.AsQueryable()
,因为DbSet<T>
实现了IQueryable<T>
。只需返回_dbSet
。 通常在通用存储库中创建一些方法来包含相关实体以进行即时加载。 - 如果您的存储库是通用的,那么为什么要使用特定的上下文?使用
DbContext
代替。 - 为什么要从存储库中暴露
DbContext
? - 您正在UoW中创建上下文。
- 将
_dbContext
设置为null是不必要的。
工作单元和存储库模式的实现在开发人员世界中仍然是一个巨大的争论的主题,尽管如此,在阅读了这么多关于这方面的内容之后,我可以给你一些我收集到的指导方针:
- 不要过度使用泛型,如果你真的需要一个泛型存储库,那么只把那些真正在它们之间共享的方法放在那里,如果你能避免所有这些,那就更好了。
- 永远不要使用基于表达式树的方法。
- 我可以给你其他的想法,但我想引导你去看我写的一篇关于这个的文章[不是因为这是我的,我真的很努力地工作],如果你愿意,你可以在这里查看。