MVC 4 Web サイトを構築しており、リポジトリ パターンに従おうとしています。
以下のような複雑なセットアップを見てきましたが、スキル レベルが原因でそれを実行できません。
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);
}
}