对于问题的不良标题,如果它是重复的,请道歉。
我有两个数据库表:
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.
我应该怎么做呢。
或者:
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
如果您使用原始sql然后您可以使用STUFF和FOR XML PATH语法,如:How Stuff and 'For Xml Path' work in Sql Server其他解决方案中所述,您首先需要通过linq从sql获取数据,然后生成结果.AsEnumerable() - 现在您可以使用string.Join函数