ef生成的SQL和属性映射/投影

本文关键字:属性 映射 投影 SQL ef | 更新日期: 2023-09-27 18:10:28

我试图重用由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语句中引用这些属性。

ef生成的SQL和属性映射/投影

您最好手工编写它。下面是一个完整的例子:

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