LINQ to EF 左连接多个条件

3

我正在尝试使用LINQ to EF复制以下SQL,但没有成功。

select * from Role
left join QueueAccess on Role.RoleId = QueueAccess.RoleId and queueId = 361

以下是我尝试过的方法。

var myAccess = (from role in entity.Role.Include(p => p.QueueAccess)
join qa in entity.QueueAccess
on new { rID = role.RoleId, qID = queueId } equals new { rID = qa.RoleId, qID = qa.QueueId }
select role).ToList();

我也尝试过这个。

var myAccess = entity.Role.Include(p => p.QueueAccess)
         .Where(x => x.QueueAccess.Any(a => a.QueueId == queueId)).ToList();

我一直只获取指定队列ID的记录,但没有获取该队列ID为空的任何其他记录。
谢谢你的帮助。
3个回答

4

我尝试了一下,但出现了异常。 System.NotSupportedException: 无法比较类型为 'System.Data.Objects.DataClasses.EntityCollection`1' 的元素。仅支持基元类型(如Int32、String和Guid)和实体类型。这与EF抱怨的(role.QueueAccess == null)有关。有没有解决方法?谢谢。 - Joe

2

试试以下方法:

var access = from role in Role
             join oq in (from q in QueueAccess
                         where q.queueId = 361
                         select q) on role.RoleId equals queue.RoleId into oqs
             from queue in oqs.DefaultIfEmpty()
             select new { role.RoleId, queue.Property };

根据我的尝试,EF不支持DefaultIfEmpty()。您能否提供一个解决方法?谢谢。 - Joe
DefaultIfEmpty 在 EF 4 中得到支持,但在 EF 1 中不支持。 - Craig Stuntz
@Joe:你的模型中有像Role.QueueAccesses这样的集合吗? - Nick Craver
Role和QueueAccess都是我的EF模型中的表,如果这是你所问的。 - Joe

0

类似这样的方式也可以运行,将条件放在ON子句而不是WHERE子句中。

join tbl3 in model.phone.Where(p => p.queue == 0  && p.phnkey == key) on x.key equals tbl3.y into a3
                            from phn in a3.DefaultIfEmpty()
                            where (phn.abc == 0 )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接