LINQ - 左外连接在Where子句中有多个参数

时间:2012-08-09 11:04:41

标签: sql linq llblgenpro

如何在LINQ中执行此SQL查询:

select * from chat c
left outer join lead s on c.key = s.id
where (typeId = 5 AND c.key = @clientId) OR (c.typeId = 4 AND s.clientId = @clientId)

或者这个SQL查询 - 相同,相同

select * from chat c
where (typeId = 5 AND c.key = @clientId) OR (typeId = 4 AND c.key in (select id from lead where clientId = @clientId))

我有什么:

var chatter = (from chat in linq.Chat
             join lead in linq.Lead
                on chat.key equals lead.Id.ToString() into clientLeads
                from cl in clientLeads.Where(l => l.clientId == clientId).DefaultIfEmpty()
            where (chat.typeId == 5 && chat.key == clientId.ToString()) ||
                (chat.typeId == 4 && chat.key == cl.Id.ToString())
                select chat).WithPath(prefetchPath).OrderByDescending(c => c.CreatedDate);

上面的LINQ查询没有得到后一个WHERE子句的任何结果,我缺少什么?

1 个答案:

答案 0 :(得分:1)

我将第二个查询翻译成linq:

var leadIds = linq.Lead.Where(l => l.clientId == clientId.ToString()).Select(l => l.id);
var chatter = from chat in linq.Chat
              where (chat.typeId == 5 && chat.key == clientId.ToString()) ||
                    (chat.typeId == 4 && leadIds.Contains(chat.key));