2013-10-20 27 views
2

我有幾個存儲庫,並希望他們實現一個接口,但實施 方法應該是相同的 - 選擇,插入等,但實施方法會改變。 有幾種選擇你可以做,什麼是更好的?如何在asp.net mvc中爲我的存儲庫製作無類型接口?

interface IRepository 
    { 
     List<T> Select(); 
     int Insert(T); 
    } 
+1

不應該是'interface IRepository '? –

回答

7

您可以創建接口,並且該接口可以在您的類中實現。

public interface IRepository<T> where T:class 
    { 
     IQueryable<T> GetAll(); 
     T GetById(object id); 
     void Insert(T entity); 
     void Update(T entity);   
    } 

可以使用庫模式和工作模式在這裏爲好單位。

public class Repository<T>:IRepository<T> where T:class 
    { 
     private DbContext context = null; 
     private DbSet<T> dbSet = null; 

     public Repository(DbContext context) 
     { 
      this.context = context; 
      this.dbSet = context.Set<T>(); 
     } 

     #region IRepository 

     public void Insert(T entity) 
     { 
      dbSet.Add(entity); 
     } 

     public IQueryable<T> GetAll() 
     { 
      return dbSet; 
     } 

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

      this.context.SaveChanges(); 
     } 

     #endregion 
    } 

在這種情況下,您可以傳遞任何類型的對象。 有關更多詳細信息和示例檢查here

相關問題