一对多连接 - 只取许多部分的最后一个
我是 EF 的新手,所以如果我的问题之前已经得到解答,我很抱歉..我只是无法弄清楚语法..
我有两个实体,Category
& 产品
,其中一个类别有多种产品。
我想获取所有类别,仅包含他们的最新产品(它有一个名为时间戳的日期属性),
我不知道该怎么做。 :-/
如果可能的话我想知道两种编写方式的语法,类似 sql 语法和类似 C# 语法,例如:
ctx.Categories.Include("Products").ToList()
from c in ctx.Categories.Include("Products")
谢谢!
I'm quite a newbie in EF, so I'm sorry if my question has been answered before.. I just can't figure out the syntax..
I have two entities, Category
& Product
, where one category has many products.
I want to get all categories, with only their latest product (it has a date property named timestamp)
I have no idea how to do that. :-/
If possible I'd like to know the syntax of the two ways to write it, both the sql-like syntax, and the C# like syntax, e.g.:
ctx.Categories.Include("Products").ToList()
from c in ctx.Categories.Include("Products")
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是类似于 SQL 的方式:
这是 Lambda 方式(警告,未经测试):
关于
Categories.Include("Products")
的注释,在您的示例中不需要它。您使用“包含”进行急切加载,因此,例如,如果您有从 EF 返回的类别列表,则当您执行 Categories.Product 时,您将获得关联的产品。但您所需要的只是一个类别列表,以及每个类别的一个产品 - 该产品已在上面的 LINQ 查询中返回,因此不需要 Include。
Here's the SQL-like way:
This is the Lambda-way (warning, untested):
A note on
Categories.Include("Products")
, you don't need this in your example. You use "Include" for eager-loading, so that for example if you had a list of Categories returned from EF, when you do Categories.Product you will get the associated product.But all you require is a list of categories, and a single product for each one - which is already returned in the above LINQ query, so no need for Include.