MVC 控制器操作中的 LINQ 导航属性?
我有点纠结这是否是最佳实践。
我有一个返回 IQueryable 的存储库。这在控制器中的用法正确吗?
var whatever = ObjectRepository.GetWhatever(id);
var videoId = whatever.UsersInObject1InObjects2.First().Object.Video.ExternalVideoId;
在上面的第二行中,“.Object”和“.Video”是对与“whatever”表相关的表的引用。
或者我应该在不同的存储库中创建另一个函数来获取ExternalVideoId?
I'm kinda stuggling with this being best practice or not..
I have a repository that returns an IQueryable lets say. Is this correct usage in the controller?
var whatever = ObjectRepository.GetWhatever(id);
var videoId = whatever.UsersInObject1InObjects2.First().Object.Video.ExternalVideoId;
Where in the 2nd line above ".Object" and ".Video" are references to tables that are related to "whatever" table.
Or should I be making another function in a different repository to get the ExternalVideoId?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常这样做的方式是这样的。我创建了一个单独的模型类,用于封装控制器需要从数据库获取的数据。 (也就是说,通常我不使用 ORM 类)。这允许我使用我可能需要的各种属性来注释模型类成员。在存储库代码中,我查询 ORM,然后返回模型类(或模型的 IQueryable/IEnumerbale)作为结果。
我听说过一种观点,不建议从 ORM(例如实体框架)返回 IQueryable,因为这样做,如果您不小心控制器/视图中的模型,则可能会冒多次对后端执行查询的风险。这是因为在 EF 中 IQueryable 表示尚未执行的查询。通过返回 IEnumerable 而不是 IQueryable,您可以确保查询执行仅限于您的存储库类。
然而我发现,有时返回 IQueryable 更方便。例如,对于表分页/排序场景,我可以在执行之前将页码、排序方向、页面大小等应用于 IQueryable。我觉得这个逻辑更多地属于控制器而不是存储库。有些人可能不同意。
The way I usually do this is this. I create a separate model class that encapsulates data that the controller need from the database. (I.e. as a rule I do not use ORM class for this). This allows me annotating the model class members with all sort of attributes I might need. In the repository code I query the ORM and then return the model class (or IQueryable/IEnumerbale of model) as the result.
I've heard an opinion that returning IQueryable from an ORM such as Entity Framework is not advised, because by doing this, you risk executing a query against your back end several times if you are not careful with your model in controller/view. This is because in EF IQueryable represent a query that is not executed yet. By returning IEnumerable instead of IQueryable you make sure that query execution is confined to your repository class.
I however find, that sometimes it's more convenient to return IQueryable. For example, for table paging/sorting scenarios I can apply page number, sort direction, page size, etc to the IQueryable before executing it. I feel that this logic belongs more to controller rather then to repository. Some may disagree.
您实际上正在做的是使用集合来执行查询。
我认为您需要更好地了解 linq 查询。
您不想将自定义查询添加到存储库。
您只想像这样公开可查询接口..
然后您可以使用 linq to sql
What you're actually doing is using a collection to do a query.
I think you need to have a better look at linq queries.
You don't want to add custom queries to your repository.
You just want to expose the queryable interface like so..
then you can use linq to sql