我正在尝试将此sql转换为linq:
SELECT [t0].[ThreadId] FROM [MessageParticipants] AS [t0]
WHERE EXISTS(
SELECT threadId
FROM [MessageParticipants] AS [t1]
WHERE ([t1].[UserId] = 23)
)
AND ([t0].[UserId] = 3)
我尝试过使用LINQPad进行转换,但我无法使用它
这几乎可以工作:
var result = from mp2 in MessageParticipants
let x = (from mp in MessageParticipants where mp.UserId == 3 select mp.UserId)
where x.Contains(23)
select mp2;
result.Dump();
以上LINQ的结果查询(这是错误的)
DECLARE @p0 Int = 23
DECLARE @p1 Int = 3
SELECT [t0].[Id], [t0].[ThreadId], [t0].[UserId], [t0].[CreatedDate], [t0].[MessageId]
FROM [MessageParticipants] AS [t0]
WHERE EXISTS(
SELECT NULL AS [EMPTY]
FROM [MessageParticipants] AS [t1]
WHERE ([t1].[UserId] = @p0) AND ([t1].[UserId] = @p1)
) --> AND should be here not in the inner query
也许有更好的方法?
我试图找到用户23和用户3是否已经通过查找threadId进行了持续对话。
所以MessageParticipants表看起来像这样:
Id, ThreadId, UserId
--------------------
1 52 23
2 52 3
3 11 20
答案 0 :(得分:2)
我相信你的sql有点关闭,你应该在表上使用连接到自己,然后使用where为id。这是更新的sql,并在相应的linq下面获取线程ID。
-- create in memory table for testing
DECLARE @MessageParticipants table (Id INT identity, ThreadId int, UserId int)
insert into @MessageParticipants(ThreadId, UserId) values (52,23), (52,3), (11, 20),(11, 3)
SELECT [t0].[ThreadId]
FROM @MessageParticipants AS [t0]
INNER JOIN @MessageParticipants AS [t1] ON t0.ThreadId = t1.ThreadId
WHERE [t1].[UserId] = 3 AND [t0].[UserId] = 23
Linq声明
var result = from m1 in MessageParticipants
join m2 in MessageParticipants on m1.ThreadId equals m2.ThreadId
where m2.UserId == 3 && m1.UserId == 23
select m1.ThreadId;
var thread = result.FirstOrDefault();