我尝试将EntityFramework 6生成的SQL重用为手动创建的SQL语句中的子选择。例如,以下查询:
dbContext.Users
.GroupBy(u => u.Email)
.Select(g => new {Email = u.Key, Name = g.Max(u1 => u1.Name)})
.ToString()
以下SQL中的结果:
SELECT
1 AS [C1],
[GroupBy1].[K1] AS [Email],
[GroupBy1].[A1] AS [C2]
FROM ( SELECT
[Extent1].[Email] AS [K1],
MAX([Extent1].[Name]) AS [A1]
FROM [dbo].[Users] AS [Extent1]
GROUP BY [Extent1].[Email]
) AS [GroupBy1]
请注意,select中的字段列表与查询返回的数据类型不匹配(有一个C1,C2不是{Email,Name}的匿名类型)。有没有办法通过查看查询属性/等来找出映射?然后,我将能够在外部SQL语句中引用这些属性。
答案 0 :(得分:0)
你最好手动编码。这是一个完整的例子:
CREATE TABLE #Users (Email varchar(200), Name varchar(200))
INSERT INTO #Users (Email, Name) VALUES ('vold@stack.com', 'Vololdymyr 1')
INSERT INTO #Users (Email, Name) VALUES ('vold@stack.com', 'Vololdymyr 2')
SELECT u.Email, MAX(u.Name) As Name FROM #Users u GROUP BY Email
DROP TABLE #Users
结果是:
Email Name
---------------------------------
vold@stack.com Vololdymyr 2