2017-06-22 30 views
0

我有界面。使用工廠存儲庫模式添加實體

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(); 
    } 

我的實體框架知識很少生疏。不知道如何實現添加,刪除方法等請給我一個提示。代碼片段受到熱烈歡迎。謝謝。

回答

0

不知道如何實現添加,刪除方法

他們在RepositoryBase已經實施。

+0

嘿,我是多麼愚蠢......我必須在方法中添加'SaveChanges()'嗎? – Bigeyes

+0

這取決於你如何處理工作單元。外部作用域可以控制DbContext生命週期,事務和SaveChanges()。 –

0

您的CatRepository繼承自您的通用RepositoryBase,其通用參數設置爲您的Cat域實體。您的AddDelete已在您的RepositoryBase課程中實施。

通用倉庫的目的是有共同的邏輯組合在一起,像Add()Delete()AddRange()DeleteRange(),和你CatRepository的目的是有非常具體的實施像GetNaughtiestCat()方法。如果您沒有這些實現,則仍然可以使用GenericRepository,其通用參數設置爲Cat,則需要刪除abstract關鍵字。