2013-12-08 111 views
0

我已經被分配了一個新的項目,並且決定給EF一個去。在這個項目中,我所做的只是獲取沒有持久性的數據。我必須實現一些緩存,就是這樣。Generic Repository EntityFramework 6 Implementation

閱讀關於存儲庫模式我發現了大量的代碼示例等......他們似乎對我來說都是錯誤的。他們實現了一對一實體到存儲庫。

在我的項目中,我只是需要讀取數據而不是保存等......只是閱讀。我有100個實體,我無法創建100個存儲庫似乎都是錯誤的。

我已經決定開始簡單,我都需要的是這樣的:

public interface IRepository : IDisposable 
{ 
    IEnumerable<T> GetAll<T>() where T : class; 
    IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class; 
    T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class; 
} 

public class Repository : IRepository 
{ 
    public IEnumerable<T> GetAll<T>() where T : class 
    { 
     return ???.ToArray(); 
    } 

    public IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return ???.Where(predicate).ToArray(); 
    } 

    public T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return ???.Where(predicate).FirstOrDefault(); 
    } 

    public void Dispose() 
    { 
     throw new NotImplementedException(); 
    } 
} 

什麼我掙扎是我把「???」那應該是我的IdbSet。

我該如何實現我的具體存儲庫?任何建議或noddy測試樣本都可以。

千恩萬謝

回答

1

首先,你最好改變GetAll()Find()方法返回的IQueryable<T>代替IEnumerable<T>,使數據集上進一步查詢會採用以下方式實現LINQ到實體。

由於EF落實,嘗試這樣的事情:

public class EFRepository : DbContext, IRepository 
{ 
    // ctor: 
    // pass a full connecting-string, or "name=someName" from configuration 
    public EFRepository(string connectionStringOrName) : base(connectionStringOrName) 
    { 
      // init sets 
      this.Entities1 = this.Set<EntityOfSomeType>(); 
      this.Entities2 = this.Set<EntityOfOtherType>(); 
    } 

    public IEnumerable<T> GetAll<T>() where T : class 
    { 
     return this.Set<T>().ToArray(); 
    } 

    public IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return this.Set<T>().Where(predicate).ToArray(); 
    } 

    public T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return this.Set<T>.FirstOrDefault(predicate); 
    } 

    public void Dispose() 
    { 
     base.Dispose(); 
    } 

    // Your DbSets... 
    public IDbSet<EntityOfSomeType> Entities1 { get; set; } 
    public IDbSet<EntityOfAnotherType> Entities2 { get; set; } 
} 

(我用DbContext與你要去代碼優先的假設)

+0

@ haim770.Thanks您reply.Yes我正在使用codefirst。 我是EF的新手,我無法獲得數據實例化dbset。是DBContext最輕的EF對象嗎?它可以在多線程環境中使用嗎? 任何建議 – user9969

+0

我爲現實生活場景增加了一些代碼。 – haim770

+0

'DbContext'不是'最輕'或'最重'的,只是EF提供的訪問/模型數據的方法之一。見http://stackoverflow.com/questions/5446316/code-first-vs-model-database-first – haim770

相關問題