2012-07-31 46 views
0

我正在從CodeFirst轉移到DatabaseFirst來映射我的視圖。在我CodeFirst的方法,我有一個基礎機構是這樣的:爲EF中的實體定義通用存儲庫DatabaseFirst

public abstract class BaseEntity 
{ 
    /// <summary> 
    /// Gets or sets the entity identifier 
    /// </summary> 
    public virtual int Id { get; set; } 
... // Some more methods here for equality checking 
} 

我得出我的所有類從這個基類,因爲他們每個人都將有一個ID。所以我使用這個BaseClass來創建一個通用的存儲庫。我的倉庫看起來是這樣的:

public partial class EfRepository<T> where T : BaseEntity 
{ 
    public readonly DemirbasContext context; 
    private DbSet<T> _entities; 

    /// <summary> 
    /// Ctor 
    /// </summary> 
    /// <param name="context">Object context</param> 
    public EfRepository(DemirbasContext context) 
    { 
     this.context = context; 
    } 

    public T GetById(object id) 
    { 
     return this.Entities.Find(id); 
    } 

    public void Insert(T entity) 
    { 
     try 
     { 
      if (entity == null) 
       throw new ArgumentNullException("entity"); 

      this.Entities.Add(entity); 

      this.context.SaveChanges(); 
     } 
     catch (Exception e) 
     { 
     ... 
     } 
    } 
    // Other methods here Update, Delete etc 

所以我能夠創建庫只需指定這樣

EfRepository<Car> carRepo = new EfRepository<Car>(); 

在DatabaseFirst泛型類型paremeter,我不能從基類派生的實體類。有沒有辦法做到這一點,或者會有什麼建議?

回答

0

糟糕,我錯過了代碼生成器。

右鍵單擊您的數據模型(.EDM文件),然後單擊添加代碼生成項目。選擇DbContext(用於簡化的DbContext API)。

這會創建兩個帶.tt擴展名的文件:一個用於上下文,一個用於實體。如果你展開文件,你會看到.tt文件保存你所有的類。

您可以根據需要對其進行修改。