我有一些遗留代码,其中有很多原始SQL语句,我尝试将其移植到LINQ。
其中一个看起来像这样
select s.Id, s.Name, s.Enabled, s.Tags, s.Description, s.ImageUrl, s.ImageFullUrl, sss.Id as StoneSupplierStoneId
from Stone s, StoneSupplierStone sss
where s.Id = sss.Stone_id and s.Enabled = 1
and sss.Id IN (select MAX(sss.Id)
from Stone s, StoneSupplierStone sss
where sss.StoneSupplier_id = 6142
and s.Id = sss.Stone_id and s.Enabled = 1
group by s.Name, (case when sss.CustomStoneName is null then s.Name else sss.CustomStoneName end))
order by s.Name
我设法使用类似的东西移植到LINQ
var sssq = from s in Stone
from sss in StoneSupplierStone
where sss.StoneSupplier_id == 6142
&& s.Id == sss.Stone_id
&& s.Enabled == true
let res = new { s.Name, sssName = sss.CustomStoneName == null ? s.Name : sss.CustomStoneName, sss.Id }
group res by new { res.Name, res.sssName } into g
select new { sssId = g.Max(_ => _.Id) };
var q = from s in Stone
from sss in StoneSupplierStone
where s.Id == sss.Stone_id
&& s.Enabled == true
&& sssq.Any(_ => _.sssId == sss.Id)
orderby s.Name
select new { s.Id, s.Name, s.Enabled, s.Tags, s.Description, s.ImageUrl, s.ImageFullUrl, StoneSupplierStoneId = sss.Id };
虽然我得到了相同的结果,但底层生成的查询看起来很奇怪
-- Region Parameters
DECLARE @p0 Int = 1
DECLARE @p1 Int = 6142
DECLARE @p2 Int = 1
-- EndRegion
SELECT [t0].[Id], [t0].[Name], [t0].[Enabled], [t0].[Tags], [t0].[Description], [t0].[ImageUrl], [t0].[ImageFullUrl], [t1].[Id] AS [StoneSupplierStoneId]
FROM [Stone] AS [t0], [StoneSupplierStone] AS [t1]
WHERE (([t0].[Id]) = [t1].[Stone_id]) AND ([t0].[Enabled] = @p0) AND (EXISTS(
SELECT NULL AS [EMPTY]
FROM (
SELECT MAX([t4].[Id2]) AS [value]
FROM (
SELECT [t2].[Id], [t2].[Name], [t2].[Enabled], [t3].[Id] AS [Id2], [t3].[StoneSupplier_id], [t3].[Stone_id],
(CASE
WHEN [t3].[CustomStoneName] IS NULL THEN [t2].[Name]
ELSE CONVERT(NVarChar(256),[t3].[CustomStoneName])
END) AS [value]
FROM [Stone] AS [t2], [StoneSupplierStone] AS [t3]
) AS [t4]
WHERE ([t4].[StoneSupplier_id] = @p1) AND (([t4].[Id]) = [t4].[Stone_id]) AND ([t4].[Enabled] = @p2)
GROUP BY [t4].[Name], [t4].[value]
) AS [t5]
WHERE [t5].[value] = [t1].[Id]
))
ORDER BY [t0].[Name]
有没有办法重写我的LINQ查询,使其看起来更像原始的SQL查询?
P.S。我使用LinqPad来测试LINQ并生成查询。