我有接口。
public interface IRepository<T> where T : class
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Expression<Func<T, bool>> filter);
然后
public interface ICatRepository : IRepository<Cat>
{
}
我也有基类。
public abstract class RepositoryBase<T> where T : class
{
private DbContext dataContext;
protected readonly IDbSet<T> dbset;
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get; private set;
}
protected DbContext 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>> filter)
{
IEnumerable<T> objects = dbset.Where<T>(filter).AsEnumerable();
foreach (T obj in objects)
dbset.Remove(obj);
}
现在我有了实现类。
class CatRepository : RepositoryBase<Cat>, ICatRepository
{
public CatRepository(IDatabaseFactory databaseFactory) : base(databaseFactory)
{
}
public void Add(Cat entity)
{
throw new NotImplementedException();
}
public void Delete(Cat entity)
{
throw new NotImplementedException();
}
public void Delete(Expression<Func<Cat, bool>> filter)
{
throw new NotImplementedException();
}
我的实体框架知识有点生疏。不确定如何实现添加、删除方法等。请给我一个提示。热烈欢迎代码片段。谢谢。
不确定如何实现添加、删除方法
它们已经在 RepositoryBase 中实现。
您的CatRepository
继承自您的泛型RepositoryBase
,其泛型参数设置为您的Cat
域实体。您的Add
和Delete
已经在您的RepositoryBase
类中实现。
通用存储库的目的是将公共逻辑组合在一起,如Add()
、Delete()
、AddRange()
、DeleteRange()
,而CatRepository
的目的是像GetNaughtiestCat()
方法一样具有非常具体的实现。如果没有这些实现,您仍然可以使用将泛型参数设置为 Cat
的 GenericRepository
,您需要删除 abstract
关键字。