如何在Linq或lambda中创建等效代码?
我正在Asp.net Core 2上使用Entity Framework Core。
SELECT
(SELECT
STUFF((SELECT DISTINCT ', ' + Roles.Name
FROM AspNetUsers Users
INNER JOIN AspNetUserRoles UserRoles ON UserRoles.UserId = Users.Id
INNER JOIN AspNetRoles Roles ON Roles.Id = UserRoles.RoleId
WHERE AspNetUsers.Id = UserRoles.UserId
FOR XML PATH('')), 1, 2, '')) AS 'Roles',
AspNetUsers.*
FROM
AspNetUsers AspNetUsers
最佳答案
我会有一个看起来像这样的查询。如果您对查询进行概要分析,则会注意到STUFF ... FOR XML PATH部分是由.NET(而不是SQL)在内存中计算的。
var test = (
from u in ctx.Users
join ur in ctx.UserRoles on u.Id equals ur.UserId
join r in ctx.Roles on ur.RoleId equals r.Id
group r by u into g
select new { User = g.Key, Roles = string.Join(",", g.Select(y => y.Name)) }
);
边注
使用查询将用户保持为对象要容易得多,而不是扩展其所有属性
关于c# - 如何在Linq或Lambda中创建Stuff和XML PATH(SQL),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50662012/