在多对一和一对多关系上实现 LINQ to Entity
我正在尝试使用 Include 扩展来实现 LINQ to Entity。
我有以下方案:
这是我的第一个 LINQ(它工作正常):
var query = ctx1.Order_Details.Include("Order").Select( o => new
{ o.OrderID,
o.ProductID,
o.Order.OrderDate,
o.Order.OrderNumber
});
这是我的第二个 LINQ (不起作用):
我的问题就是为什么当我在“多对一”关系上实现 Linq 时,LINQ 可以正常工作,而当我尝试“由内而外”(即一对多)实现 LINQ 时,它不起作用?
I'm tring to implement LINQ to Entity using Include extension.
I have the following scheme:
Here is my first LINQ (it works properly):
var query = ctx1.Order_Details.Include("Order").Select( o => new
{ o.OrderID,
o.ProductID,
o.Order.OrderDate,
o.Order.OrderNumber
});
Here is my second LINQ(doesn't work):
My question is why when I'm implementing Linq on "many to one" relationship LINQ works properly and when I'm trying to implement LINQ "inside out" (i.e. one to many) it doesn't work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个查询有效,因为每个订单详细信息只有一个相关订单 - 您正在从“n”角度(订单详细信息)查看关系。
在第二个查询中,您从 Order 和 Order_Detail 之间 1:n 关系中的“1”开始,并且您试图获取一个单价 - 但有一个集合(“n”)相关的统一价格和数量。仅当每个
Order
只有一个相关的Order_Detail
时,您当前的方法才有效。如果您想以匿名类型获取相关的单价和数量集合,您可以执行以下操作:
The first query works because there is just one related order for each order detail - you are looking at the relationship from the "n" perspective (the order details).
In the second query you are starting with the "1" in the 1:n relationship between Order and Order_Detail and you are trying to get one unit price - but there is a collection (the "n") of related united prices and quantities. Your current approach would only work if there is just one related
Order_Detail
for eachOrder
.If you wanted to grab the related unit price and quantities collections in your anonymous type you could do something like this:
只是一个猜测,但是怎么样:
Just a guess, but how about: