在單個查詢中Linq to Sql中的連鎖列表

[英]Concatenated Lists in Linq to Sql in a single query


I have this sql query (simplified for the example):

我有這個SQL查詢(簡化示例):

;WITH info as (
    --actually a complex multi table query, just simplified
    select UserID, RoleName
    from UserRole
),
AccountUsers as
(
    select distinct UserID
    from info
)
select UserID,
Roles = STUFF(
(
  SELECT ', ' + l.RoleName 
    FROM info AS l
    WHERE l.UserID = au.UserID
    FOR XML PATH(''), TYPE
).value('.[1]','nvarchar(max)'), 1, 2, '')
from AccountUsers au

Is it possible to convert this into linq-to-sql so that it generates a single query? I have over 500 users and probably around a dozen or so roles. It doesn't have to generate the same query, just the same results.(Built a demo of the sql here http://sqlfiddle.com/#!6/c54fc/4 )

是否可以將其轉換為linq-to-sql以便生成單個查詢?我有超過500個用戶,可能有大約十幾個角色。它不必生成相同的查詢,只需要相同的結果。(在這里建立一個sql的演示http://sqlfiddle.com/#!6/c54fc/4)

(edit: added linq) This is the linq I have that is generating multiple queries:

(編輯:添加linq)這是我生成多個查詢的linq:

var userroles = dc.UserRoles
    .Select(ua => new
    {
        ua.UserID,
        Roles = string.Join(", ", 
            dc.UserRoles
                .Where(ur => ur.UserID == ua.UserID )
                .Select(ur => ur.RoleName)
                .Distinct())
    });

1 个解决方案

#1


0  

I'm sorry I don't know if this will work for Linq to SQL, but this is how you might do it with a list of classes:

對不起,我不知道這是否適用於Linq to SQL,但是你可以用一個類列表來實現它:

var groupedUserRoles = userRoles
    .GroupBy(ur => ur.UserID)
    .Select(ur => new
        {
            UserId = ur.Key,
            Roles = ur.Select(r => r.RoleName)
        })
    .ToList();

groupedUserRoles.ForEach(ur => 
    Console.WriteLine($"UserID: {ur.UserId}, Roles: {string.Join(", ", ur.Roles)}"));

Output

產量

enter image description here


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/08/09/7299835fd67c8ee800772adc411d05a9.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com