LINQ 中的简单查询
我有3张桌子。基本上,我有这样的结构:
Customer
--------
IDCustomer
NameCustomer
Product
«««««««
IDProduct
NameProduct
Order
«««««
IDCustomer
IDProduct
如何使用 LINQ 获得这样的结果:
Result
««««««
NameCustomer
NameProduct
提前致谢!
I have 3 tables. Basically, I have this structure:
Customer
--------
IDCustomer
NameCustomer
Product
«««««««
IDProduct
NameProduct
Order
«««««
IDCustomer
IDProduct
How to get a result like this, using LINQ:
Result
««««««
NameCustomer
NameProduct
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您没有在数据库中设置正确的关系(或者您没有为关系生成导航属性),您可以执行以下操作:
不过,将正确的外键添加到数据库会更容易并允许实体框架(或 LINQ to SQL)为您生成导航属性。如果是这样的话,那就很简单了:
Assuming you don't have proper relationships set up in the database (or you haven't generated navigation properties for your relationships), you could do the following:
It would be much easier, though, to add the proper foreign keys to the database and allow Entity Framework (or LINQ to SQL) generate the navigation properties for you. If that were the case, it would be as easy as:
LINQ 的全部优点在于,这一切都应该通过自动生成的对象自动为您完成。
在将表关系移动到 DBML 文件之前,请确保在 SQL Server 中设置表关系。此后,您的客户表将附加订单,其中您的产品将附加到您的订单。
例如,从客户表 (LINQ) 中进行选择将为您提供一个客户列表,其中每个客户都会附加一个 IEnumerable 订单对象列表。
The whole beauty of LINQ is that this should be all automatically done for you with automatically generated objects.
Make sure your table relationships are setup in SQL Server before moving them to your DBML file. After this, your Customer table will have Orders attached to it, in which your Products will be attached to your orders.
Such as selecting from your customer table (LINQ) will give you a list of Customers, in which will have an IENumerable list of Order objects attached to each.
您可以使用 linqpad.exe 直接针对数据库测试 linq 查询
you can use linqpad.exe to test your linq query directly against your database