2011-04-24 66 views
7

我正在尋找完整的ef知識庫接口(和實現)。我有這個:完整的實體框架知識庫接口

public interface IRepository<T> where T: class 
{ 
    IQueryable<T> GetQuery(); 

    IEnumerable<T> GetAll(); 
    IEnumerable<T> Find(Func<T, bool> where); 
    T Single(Func<T, bool> where); 
    T First(Func<T, bool> where); 

    void Delete(T entity); 
    void Add(T entity); 
    void Attach(T entity); 
    void SaveChanges(); 
} 

而我期待的所有方法的接口包括SingleOrDefault等。
我在哪裏可以找到這樣的東西?

+4

'的SingleOrDefault()'是'IEnumerable的' – 2011-04-25 00:11:22

+0

@Bala爲r的擴展方法:我知道,我很期待爲了完成所有IObjectSet的接口和實現,我可以公開所有的方法。 – Naor 2011-04-25 00:19:00

回答

10

定義存儲庫有兩種方法。首先是通過暴露IQueryable的是夠做任何事:

public interface IRepository<T> where T: class 
{ 
    IQueryable<T> GetQuery(); 

    // This method requires additional knowledge about entity 
    // or more compilcated approach. The point of the method 
    // is to check EF's internal storage first before querying DB 
    // T GetById(int Id);   

    void Delete(T entity); 
    void Add(T entity); 
    void Attach(T entity); 
} 

擁有一個像GetAllFirst東西簡直是多餘的,因爲GetQuery服務器這一切。第二種方法是特定的儲存庫,你不要暴露IQueryable

public interface IRepository<T> where T : class 
{ 
    IEnumerable<T> GetAll(); 

    // Expressions!!!! Func will load all items to memeory 
    // and then perform filtering by linq-to-objects!!!!!! 
    IEnumerable<T> Find(Expression<Func<T, bool>> where); 
    T Single(Expression<Func<T, bool>> where); 
    T First(Expression<Func<T, bool>> where); 

    void Delete(T entity); 
    void Add(T entity); 
    void Attach(T entity); 
} 

第二個版本,然後通過添加方法,如GetXXXOrderedByName,GetXXXWithRelatedYYY等具體信息庫接口派生

還有一點就是SaveChanges通常不是存儲庫的一部分,因爲您可能需要修改多個存儲庫中的項目,並通過單一方法將更改保存在所有存儲庫中。爲此目的存在另一種模式 - 工作單元。

+0

通常不是部分,但EF環境本身就是一個工作單元。 – Rushino 2011-09-14 13:45:40

0

您可以在IEnumerable here上找到所有方法的列表。

0

您只需從nuget包管理器安裝T4Scaffolding nuget包即可。

這個包安裝到你的模型類庫項目或新項目的類庫稱爲庫

然後在包管理器控制檯選擇模型類庫項目然後鍵入

支架庫[DomainClasses.Alias] - DbContextType:ContextClass]

enter image description here

你得到生成的接口和實現倉庫類爲您的域類

,如果你使用Visual Studio 2015年,我建議你使用nugetPackage T4Scaffolding.VS2015

enter image description here

如果要概括你的資料庫,然後你可以和T實體替換類

有關詳細信息,http://thedatafarm.com/data-access/using-t4scaffolding-to-create-dbcontext-and-repository-from-domain-classes/