[英]Linq to SQL - Order By related Table using a Where Clause
I have two related tables lets say:我有两个相关的表可以说:
Table Products (Main Table)表产品(主表)
Table Parts (Child of Products, contains detailled Information)表部件(产品的子级,包含详细信息)
I would like to get Products ordered by the value of a specific part (eG Engine)我想按特定零件的价值订购产品(eG 引擎)
I came up with the following:我想出了以下内容:
// Code to construct a query to get all desired products
products = products.OrderBy(c => c.Parts.Where(d => d.PartName == "Engine").Select(d => d.Value).FirstOrDefault());
This works but is too slow.这可行,但太慢了。 Can I improve the query or will I have to redsign my database so I won't be sorting like this in the first place?我可以改进查询还是我必须重新设计我的数据库,这样我就不会首先像这样排序?
Generated SQL-Query:生成的 SQL 查询:
SELECT
[Project3].[ID] AS [ID],
[Project3].[Name] AS [Name]
FROM ( SELECT
[Project2].[ID] AS [ID],
[Project2].[Name] AS [Name],
[Project2].[C1] AS [C1]
FROM ( SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name],
(SELECT TOP (1)
[Extent2].[PartValue] AS [PartValue]
FROM [dbo].[Parts] AS [Extent2]
WHERE ([Extent1].[ID] = [Extent2].[ProductID]) AND (N'Engine' = [Extent2].[PartName])) AS [C1]
FROM [dbo].[Products] AS [Extent1]
WHERE (1 = [Extent1].[Type])
) AS [Project2]
) AS [Project3]
ORDER BY [Project3].[C1] ASC
If you want to try a join, it would be a bit like this:如果你想尝试加入,它会有点像这样:
Products
.Join(Parts, pd => pd.ID, pt => pt.ProductID, (pd, pt) => new { pd.Name, pt.PartName, pt.PartValue })
.Where(x => x.PartName == "Engine")
.OrderBy(x => x.PartValue);
This would result in a single select statement without the inner selects from before这将导致单个 select 语句没有之前的内部选择
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.