我正在构建一个 MVC 4 网站,并且正在尝试遵循存储库模式。
我见过一个复杂的设置,如下所示,但由于我的技能水平,我无法完成:
public interface IEntityRepository<T>
where T : class, IEntity, new()
{
void CommitChanges();
void DeleteOnCommit(T entity);
T GetEntity(int key);
IQueryable<T> GetAll();
int InsertOnCommit(T entity);
}
由于简单,我选择了这种方法:
public class EntityAdminRepository : IAdminRepository {
AdminEntities db = new AdminEntities();
public Models.Product CreateNewProduct(Models.Product productToCreate) {
db.Products.Add(productToCreate);
return productToCreate;
}
public void DeleteProduct(int id) {
db.Products.Remove(GetProductByID(id));
}
public Models.Product GetProductByID(int id) {
return db.Products.FirstOrDefault(d => d.ID == id);
}
public IEnumerable<Models.Product> GetAllProducts() {
return db.Products;
}
public Models.Category CreateNewCategory(Models.Category categoryToCreate) {
throw new NotImplementedException();
}
public void DeleteCategory(int id) {
throw new NotImplementedException();
}
public Models.Category GetCategoryByID(int id) {
throw new NotImplementedException();
}
public IEnumerable<Models.Category> GetAllCategories() {
throw new NotImplementedException();
}
public int SaveChanges() {
return db.SaveChanges();
}
}
除了扩大规模的问题(我认为无论如何都会存在于其他地方)这个解决方案是否如此可怕,我应该立即放弃它并继续努力,直到我能够理解并实施最初的例子?
更新 1: 我使用第一种方法的问题是我不知道如何在控制器中重新创建以下功能:
protected IAdminRepository _repository;
public AdminController() : this(new EntityAdminRepository()) { }
public AdminController(IAdminRepository repository) {
_repository = repository;
}
这种方式意味着我对每个 DTO 都有一个实体,这一切如何共同达到高潮?
更新 2:
public class DatabaseRepository<T> : IRepository<T>
: where T:class, IEntity, new()
{
private DbContext context = new MyDbContext(); // proper data actions
public T GetEntity(int id)
{
return context.Tables<T>.FirstOrDefault(x => x.Id == id);
}
}
public class InMemoryRepository<T> : IRepository<T>
: where T:class, IEntity, new()
{
private List<T> context = new List<T>(); // stuff for unit testing
public T GetEntity(int id)
{
return context.FirstOrDefault(x => x.Id == id);
}
}