我們開始在我們公司開發一個小框架,在不同的應用程序之間共享代碼。對於數據訪問,我們使用EF4。我們有一個自定義的DbContext類和通用存儲庫:實體框架 - 如何使用自定義DbContext實現存儲庫?
public class RMDbContext : DbContext
{
// ....
}
public interface IRepository
{
IQueryable<T> All();
void Delete(T entity) where T : class;
void Add(T entity) where T : class;
void Update(T entity) where T : class;
int SaveChanges();
void RollbackChanges();
}
這裏的問題是如何實現資源庫,利用我們的自定義的DbContext類(RMDbContext)。我的同事認爲,最好的辦法就是讓RMDbContext實現IRepository接口:
public class RMDbContext : DbContext, IRepository
{
// ....
}
說實話,我不喜歡這種做法,因爲上下文被綁定到特定的合約(IRepository)。 IMO最好創建一個使用RMDbContext的存儲庫實現,如下所示:
public class Repository<T> : IRepository where T : RMDbContext, new()
{
protected readonly RMDbContext context;
public class Repository()
{
context = new T();
}
// ....
}
您對這兩種方法有什麼看法?你會選擇哪一個,爲什麼?
[EF4 CTP5版本庫模式]可能的重複版本(http://stackoverflow.com/questions/5066282/repository-pattern-with-ef4-ctp5) – jrummell
這不是重複的那篇文章。我有2個場景,我想知道每種方法的優點和缺點:1)讓自定義DbContext實現IRepository,或2)創建一個單獨的類,實現IRepository接口並使用自定義的DbContext對象 –