在控制器中使用 linq 查询是一个好习惯吗?
我对MVC模式不是很熟悉。您能告诉我以下三个控制器操作中哪一个更好?谢谢:)
(1) 正在执行查询:
public ActionResult List()
{
var query = repository.Query().Where(it => it.IsHandled).OrderBy(it => it.Id);
// ...
}
(2) 正在执行服务查询:
public ActionResult List()
{
var items = service.GetHandledItemsOrderById();
// ...
}
(3) 正在执行订单:
public ActionResult List()
{
var items = service.GetHandledItems().OrderBy(it => it.Id);
// ...
}
如果我们选择(1),那么控制器中的业务逻辑太多了?
如果我们选择(2),可能会有很多像GetXXXByYYY()
这样的服务方法。
如果我们选择(3),为什么我们封装 Where(it => it.IsHandled)
而不是OrderBy(it => it.Id
。
有什么想法吗?
I'm not very familiar with the MVC pattern. Could you tell me which one of the following three controller actions is better? Thanks :)
(1) Have query in action:
public ActionResult List()
{
var query = repository.Query().Where(it => it.IsHandled).OrderBy(it => it.Id);
// ...
}
(2) Have query in service:
public ActionResult List()
{
var items = service.GetHandledItemsOrderById();
// ...
}
(3) Have order by in action:
public ActionResult List()
{
var items = service.GetHandledItems().OrderBy(it => it.Id);
// ...
}
If we choose (1), then we have too much business logic in controller?
If we choose (2), there might be lots of service methods like GetXXXByYYY()
.
If we choose (3), why we encapsulate Where(it => it.IsHandled)
but notOrderBy(it => it.Id
.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我确信意见可能会有所不同,但我已经学会了尝试在服务中保留尽可能多的业务逻辑。 3将是我的选择。有了 1,您就已经发现了问题。使用 2,您将在服务中引入显示优先级。使用 3,您可以在必要时处理显示首选项。如果您要向业务层引入另一个接口,则选择 2 可能会导致不必要的代码迭代。
I'm sure opinions may vary, but I've learned to try to keep as much business logic in the service as you can. 3 would be my choice. With 1, you've already spotted the issue. With 2, you are introducing display precedence in a service. With 3, you handle display preferences where necessary. If you were to introduce another interface to your business layer, you are requiring potentially, unnecessary code iterations by choosing 2.
这要看情况。 :)
我的观点:
我喜欢保持我的服务宽松,以尽量减少重复代码。我也是管道和过滤器的粉丝。
这就是我要做的(并且确实要做的)。
Service
ItemFilters.cs
OrderingOptions.cs
这样,您可以在控制器中指定排序:
上面和选项3之间的差异:
It depends. :)
My opinion:
I like to keep my service loose, to minimize duplicate code. I'm also a fan of pipes and filters.
Here's what i'd do (and DO do).
Service
ItemFilters.cs
OrderingOptions.cs
This way, you can specify the ordering in the Controller:
Differences between the above and options 3: