views:

853

answers:

2

I am trying to replicate the following SQL using LINQ to EF but with no luck.

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

Here's what I've tried.

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();

Also tried this.

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

I keep on getting only the record with the specified queueId but none of the other records where the queueId is null.

Thanks for your help.

A: 

Try something like this:

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 };
Nick Craver
DefaultIfEmpty() isn't supported in EF from what I've tried. Would you be able to offer a work around? Thanks
Joe
`DefaultIfEmpty` is supported in EF 4 but not in EF 1.
Craig Stuntz
@Joe: Do you have a collection like Role.QueueAccesses in your model?
Nick Craver
Role and QueueAccess are both tables in my EF model if that is what you are asking.
Joe
+1  A: 

It's nearly always a mistake to use join in LINQ to Entities. Instead, do:

var myAccess = (((ObjectQuery)from role in entity.Role
                              where role.QueueAccess.Any(a => a.QueueId == queueId)
                              select role).Include("QueueAccess")).ToList();
Craig Stuntz
I gave this a go and got an exception. System.NotSupportedException: Cannot compare elements of type 'System.Data.Objects.DataClasses.EntityCollection`1'. Only primitive types (such as Int32, String, and Guid) and entity types are supportedThis is in relation to (role.QueueAccess == null) that EF is complaining about. Is there a way around this? Thanks
Joe
Oh, I see -- it's one to many. I'll fix that.
Craig Stuntz