存储库模式应该使用ObjectSetvs IDbSet< T>对于基类
本文关键字:于基类 IDbSet 基类 vs ObjectSet 存储 模式 | 更新日期: 2023-09-27 18:16:12
我试图创建一个基于MyFinance
的基础存储库类,首先使用实体框架代码。我想改变它,只使用实体框架。示例使用IDbSet
,但我不知道如何将其更改为只是香草实体框架。也许是ObjectSet<T>
?当我使用ObjectSet<T>
时,我失去了一些方法,比如GetById
,所以也许这不是100%正确的。如有任何帮助,我将不胜感激。
首先使用实体框架代码的示例库基础
public abstract class RepositoryBase<T> where T : class
{
private MyFinanceContext dataContext;
private readonly IDbSet<T> dbset;
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get; private set;
}
protected MyFinanceContext DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
dbset.Add(entity);
}
public virtual void Update(T entity)
{
dbset.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
dbset.Remove(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbset.Remove(obj);
}
public virtual T GetById(long id)
{
return dbset.Find(id);
}
public virtual T GetById(string id)
{
return dbset.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return dbset.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return dbset.Where(where).FirstOrDefault<T>();
}
}
我认为我应该改变它为EntityFramework
public abstract class BaseRepository<T> where T : class
{
private MyDBContainer _dataContext;
private readonly ObjectSet<T> dbset;
protected BaseRepository(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.CreateObjectSet<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected MyDBContainer DataContext
{
get { return _dataContext ?? (_dataContext = DatabaseFactory.DataContext); }
}
public virtual void Add(T entity)
{
dbset.AddObject(entity);
}
//public virtual void Update(T entity)
//{
// dbset.Attach(entity);
// _dataContext.Entry(entity).State = EntityState.Modified;
//}
public virtual void Delete(T entity)
{
dbset.DeleteObject(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbset.DeleteObject(obj);
}
//public virtual T GetById(long id)
//{
// return dbset.(id);
//}
//public virtual T GetById(string id)
//{
// return dbset.Find(id);
//}
public virtual IEnumerable<T> GetAll()
{
return dbset.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return dbset.Where(where).FirstOrDefault<T>();
}
}
ObjectSet<T>
是DbSet<T>
及其相关接口IDbSet<T>
的前身。然而,没有,因为我相信你已经发现了一个IObjectSet<T>
,但你是正确的,你应该使用ObjectSet<T>
代替DbSet<T>
。