Linq to SQL用分隔符追加多个记录

问题描述 投票:4回答:2

对于问题的不良标题,如果它是重复的,请道歉。

我有两个数据库表:

Users                 Documents
-------               --------- 
ID                    ID
Name                  DocumentName
                      UserID

说我在Users有1条记录

1, "bob" 

Documents的三个相关记录

1, "Doc1", 1
2, "Doc2", 1
3, "Doc3", 1

我想生成一个结果集:

1, "bob", "Doc1, Doc2, Doc3"

我尝试了各种涉及合并多个结果集但得到错误的事情:Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.

我应该怎么做呢。

c# .net linq-to-sql
2个回答
5
投票

或者:

  • 从服务器“按原样”获取列并在C#中执行concat
  • 写一个执行它的SP,然后通过LINQ调用SP

SP(接受@UserID)可以这样做:

DECLARE @txt varchar(max)
SET @txt = ''
SELECT @txt = @txt + [DocumentName] + ', '
FROM [Documents]
WHERE [UserID] = @UserID

SELECT [ID], [Name], @txt AS [Docs]
FROM [Users]
WHERE [ID] = @UserID

0
投票

如果您使用原始sql然后您可以使用STUFF和FOR XML PATH语法,如:How Stuff and 'For Xml Path' work in Sql Server其他解决方案中所述,您首先需要通过linq从sql获取数据,然后生成结果.AsEnumerable() - 现在您可以使用string.Join函数

© www.soinside.com 2019 - 2024. All rights reserved.