我有CompanyController和DepartmentController:
public class CompanyController : BaseBackendController
{
private ICompanyRepository repository;
public CompanyController(ICompanyRepository repository)
{
this.repository = repository;
}
...
[HttpPost]
public ActionResult BatchDelete(long[] ids)
{
var entities = repository.GetList().Where(item => ids.Contains(item.ID));
repository.BatchDelete(entities);
return RedirectToAction("Index");
}
}
public class DepartmentController : BaseBackendController
{
private IDepartmentRepository repository;
public DepartmentController(IDepartmentRepository repository)
{
this.repository = repository;
}
...
[HttpPost]
public ActionResult BatchDelete(long[] ids)
{
var entities = repository.GetList().Where(item => ids.Contains(item.ID));
repository.BatchDelete(entities);
return RedirectToAction("Index");
}
}
你可以看到BatchDelete的逻辑是相同的,我希望它放在父控制器上,但存在一个挑战,即存储库。我无法调用基本控制器repository.GetList()。
答案 0 :(得分:2)
您必须在存储库界面中具有一些共性。例如,您可以这样做:
public interface IRepository<T>
{
IEnumerable<T> GetList();
void DeleteBatch(IEnumerable<T> entities);
// other methods here
}
你有:
public interface ICompanyRepository : IRepository<T>
和
public interface IDepartmentRepository : IRepository<T>
然后您可以像这样设置基本控制器:
public abstract class DataController<TModel> : Controller
{
protected IRepository<TModel> repository;
public DataController(IRepository<TModel> repository)
{
this.repository = repository;
}
[HttpPost]
public ActionResult BatchDelete(long[] ids)
{
var entities = repository.GetList().Where(item => ids.Contains(item.ID));
repository.BatchDelete(entities);
return RedirectToAction("Index");
}
}
更新然后您的CompanyController将如下所示:
public CompanyController : DataController<Company>
{
public CompanyController(IRepository<Company> repository) : base(repository)
{
}
}
这样就可以了。
另外需要注意的是,您的GetList()似乎正在从数据库中获取所有,然后选择要删除操作的删除操作。最好从数据库中检索仅您感兴趣的那个并保存显着的性能。
答案 1 :(得分:1)
这就是孩子们,这就是我们将服务传递给控制器而不是原始存储库的原因。