跨多对多的 LINQ 语法
我在 LINQ 上遇到了一些困难,正在寻求帮助。我可以在 SQL 中做到这一点,但似乎无法弄清楚如何在 LINQ 中做到这一点。 我有一个 SQL Compact 4.0 数据库,并使用 C# 对其进行建模的 Entity Framework 4.0 EDMX。
这是场景,这些表:
客户 - OrderDetails - 订单
OrderDetails 表是一个非有效负载表,只是方便多对多连接。
如果给我一个 CustomerId 编号作为参数,我想返回一个 IEnumerable
。
在 SQL 中我会这样写:
SELECT Orders.*
FROM OrderDetails INNER JOIN
Orders ON OrderDetails.OrderId = Orders.OrderId INNER JOIN
Customers ON OrderDetails.CustomerId = Customers.CustomerId
How can I do this in LINQ?
I've been struggling with LINQ a bit, and was after help. I could do it in SQL, but can't seem to work out how to in LINQ.
I have a SQL Compact 4.0 Database, with a Entity Framework 4.0 EDMX modelling it, in C#.
This is the scenario, these tables:
Customers - OrderDetails - Orders
The OrderDetails table is a non-payload table, just facilitating the many to many join.
If I'm given an CustomerId Number as a parameter, I want to return an IEnumerable<Orders>
.
In SQL I would've written this as:
SELECT Orders.*
FROM OrderDetails INNER JOIN
Orders ON OrderDetails.OrderId = Orders.OrderId INNER JOIN
Customers ON OrderDetails.CustomerId = Customers.CustomerId
How can I do this in LINQ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想“用 SQL 思考”,您可以将其作为查询表达式来执行,如下所示:
请注意,这实际上根本不触及 Customers 表...我假设有足够的关系约束来确保
OrderDetails.CustomerId
确实指的是真实的客户。但是,如果您已正确设置所有关系,则可以使用 Sjoerd 的答案之类的内容。请注意,这将首先获取
Customer
实体,而上面的查询则不会。不过,这是一种更加面向对象的思考方式。编辑:看来您的关系已正确设置,有两个选项:
If you want to "think in SQL", you can do this as a query expression like this:
Note that this doesn't actually touch the Customers table at all... I'm assuming that there are enough relational constraints to ensure that
OrderDetails.CustomerId
really does refer to a real customer.If you have all the relationships set up appropriately, however, you can use something like Sjoerd's answer. Note that that will first fetch the
Customer
entity, whereas the above query doesn't. It's a more OO way of thinking about things though.EDIT: As it appears your relationships are set up appropriately, two options:
像这样的东西:
Something like this:
我认为这可行:
I think this could work :
如果您想要所有订单至少有一个 ID 为
customerId
的客户,您也可以尝试以下操作:一个订单可以有多个客户,这对我来说有点奇怪,但这就是我对您的描述的理解:“客户- OrderDetails - Orders ... OrderDetails 表是一个非有效负载表,只是促进多对多连接。”
我期望 EntityModel 中的
Order
具有Customers
的导航集合,而OrderDetails
只是一个内部联接表,不作为实体存在。If you want all orders which have at least one customer with ID
customerId
you could also try this:It looks somewhat weird to me that one order can have many customers but that's how I understand your description: "Customers - OrderDetails - Orders ... The OrderDetails table is a non-payload table, just facilitating the many to many join."
I'm expecting that an
Order
in your EntityModel has a navigation collection ofCustomers
andOrderDetails
is only a internal join table not existing as an entity.