我有界面。使用工廠存儲庫模式添加實體
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();
}
我的實體框架知識很少生疏。不知道如何實現添加,刪除方法等請給我一個提示。代碼片段受到熱烈歡迎。謝謝。
嘿,我是多麼愚蠢......我必須在方法中添加'SaveChanges()'嗎? – Bigeyes
這取決於你如何處理工作單元。外部作用域可以控制DbContext生命週期,事務和SaveChanges()。 –