如何根据存储库模式在控制器之间共享相同的操作逻辑
我有 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()。
I have CompanyController and 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");
}
}
You can see that logic of BatchDelete is the same and I want it place to parent controller, but there is a challenge, the repository. I cant call in base controller repository.GetList().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的存储库界面必须具有一些通用性。例如,您可以这样做:
在您拥有的地方:
然后
您可以像这样设置您的基本控制器:
UPDATE 然后您的 CompanyController 将如下所示:
这样就可以了。
另请注意,您的 GetList() 似乎正在从数据库中获取所有 实体,然后选择要删除的实体进行删除操作。最好从数据库中仅检索您感兴趣的内容,这样可以显着提高性能。
You have to have some commonality in your repository interface. For example, you could this do:
where you have:
and
Then you can set up your base controller like this:
UPDATE Then your CompanyController will look like this:
This will do the trick.
One other note of caution it looks like your GetList() is getting all entites from the database and then select the one you want to delete for the delete operation. Better to retrieve only the one you are interested from the database and save significant performance.
孩子们,这就是我们将服务传递给控制器而不是原始存储库的原因。
This, children, is why we pass services to Controllers, not raw repositories.