我正在尝试使用实体框架中的通用存储库,并且遇到了以下代码:
public class GenericRepository<TContext, TEntity> : IGenericRepository<TEntity>
where TContext : IUnitOfWork
where TEntity : class
{
protected TContext _context;
/// <summary>
/// Constructor that takes a context
/// </summary>
/// <param name="context">An established data context</param>
public GenericRepository(TContext context)
{
_context = context;
}
public IQueryable<TEntity> Select()
{
return _context.Set<TEntity>().AsQueryable();
}
public IEnumerable<TEntity> GetAll()
{
return _context.Set<TEntity>().AsEnumerable();
}
public IEnumerable<TEntity> Where(Func<TEntity, bool> predicate)
{
return _context.Set<TEntity>().Where(predicate);
}
public TEntity GetSingle(Func<TEntity, bool> predicate)
{
return _context.Set<TEntity>().Single(predicate);
}
public TEntity GetFirst(Func<TEntity, bool> predicate)
{
return _context.Set<TEntity>().First(predicate);
}
public void Add(TEntity entity)
{
if (entity == null)
throw new ArgumentException("Cannot add a null entity");
_context.Set<TEntity>().Add(entity);
}
public void Delete(TEntity entity)
{
if (entity == null)
throw new ArgumentException("Cannot delete a null entity");
_context.Set<TEntity>().Remove(entity);
}
public void Attach(TEntity entity)
{
if (entity == null)
throw new ArgumentException("Cannot attach a null entity");
_context.Set<TEntity>().Attach(entity);
}
#region IDisposable implementation
private bool disposedValue;
public void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if (disposing)
{
// dispose managed state here if required
}
// dispose unmanaged objects and set large fields to null
}
this.disposedValue = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
但是我觉得有点难以理解创建构造函数的需要
/// <summary>
/// Constructor that takes a context
/// </summary>
/// <param name="context">An established data context</param>
public GenericRepository(TContext context)
{
_context = context;
}
有人可以解释一下这个用法吗?
由于
答案 0 :(得分:2)
那是因为你的项目中可能有多个DbContext类,所以你需要注入一个特定的DbContext实例来告诉GenericRepository类你正在使用哪个DbContext。
您需要拥有多个DbContext类的原因可能是:
您的项目定位到多个数据库;
您的项目很大,为了考虑性能和可维护性,您希望将其拆分为多个模块。例如:
public class BaseContext<TContext> : DbContext
where TContext : DbContext, new()
{
protected BaseContext()
: base("name=ConnectionString")
{
}
}
public class ShopDbContext :BaseContext<ShopDbContext>
{
public DbSet<Product> Products{ get; set; }
}
public class BlogDbContext :BaseContext<BlogDbContext>
{
public DbSet<Blog> Blogs{ get; set; }
}
现在,如果要查询Products,则必须实例化ShopDbContext,并将其传递给GenericRepository构造函数(IoC是一个不错的选择)。