如何将以下产生正确结果的T-SQL查询转换为C#中的LINQ表达式?
WITH CTE
AS ( SELECT RN = ROW_NUMBER() OVER ( PARTITION BY dbo.Product.ID ORDER BY dbo.Picture.UpdatedDate ASC )
,Product.ID
,Product.Name
,Picture.Path
FROM Dbo.Product
INNER JOIN dbo.Product_Picture_Mapping
ON dbo.Product_Picture_Mapping.ProductID = dbo.Product.ID
INNER JOIN dbo.Picture
ON dbo.Picture.ID = dbo.Product_Picture_Mapping.PictureID)
SELECT ID AS 'ID'
,Name AS 'Name'
FROM CTE
WHERE RN = 1
我尝试过以下代码。
var result= (from c in cd.Product
join pp in cd.Product_Picture_Mapping
on c.ID equals pp.ProductID
join pcc in cd.Picture
on pp.PictureID equals pcc.ID
select new ProductViewModel() { PicturePath = pcc.Path, ProductName = c.Name, ProductID = c.ID}).ToList();
答案 0 :(得分:0)
查看以下内容是否有效:
var result= (from c in cd.Product
join pp in cd.Product_Picture_Mapping
on c.ID equals pp.ProductID
let pcc = pp.Pictures.FirstOrDefault()
select new ProductViewModel()
{
PicturePath = pcc.Path,
ProductName = c.Name,
ProductID = c.ID
}).ToList();
查看您的表名,看起来您有一个多表(product_picture_mapping),EF可以优化,让您可以选择执行以下操作:
var result = from c in cd.Product
let ppc = c.Pictures.FirstOrDefault()
select new ProductViewModel
{
PicturePath = pcc.Path,
ProductName = c.Name,
ProductID = c.ID
};