Left join question

Posts   
 
    
Ian avatar
Ian
User
Posts: 511
Joined: 01-Apr-2005
# Posted on: 14-May-2010 20:56:35   

Hi there,

Take this Linq To LLBLGen query snippet...

from a in m.Account
join ac in m.VwAccountConfirmation on a.AccountId equals ac.AccountId into acg
from acgitem in acg.DefaultIfEmpty()
where acgitem.AccountId == null

The aim here is to do a left join and only return rows for which there's no row to join to.

"acgitem.AccountId" is an int32 and its not nullable. So why is the compiler letting me compare it with null? (This query works)

Also I'm getting a code hint or something for 'acgitem.AccountId == null' that may be Resharper and it says... 'Expression is always false'. I suppose an int32 is never going to be null - is this what it means?

Cheers, Ian.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 16-May-2010 23:01:24   

The expression could be different when it's translated to sql, so it could be that ReSharper complains but still valid. Now this is not the case, the comparison to NULLl is not necessary. In the generated sql correct, right?

David Elizondo | LLBLGen Support Team
Ian avatar
Ian
User
Posts: 511
Joined: 01-Apr-2005
# Posted on: 17-May-2010 04:47:36   

Yes it works fine. Why do you think the comparison to NULL is not necessary? Without it the query would return all the rows for which there's a match in VwAccountConfirmation for each Account. I only want the Accounts which don't have a corresponding row in VwAccountConfirmation.

Walaa avatar
Walaa
Support Team
Posts: 14994
Joined: 21-Aug-2005
# Posted on: 17-May-2010 09:48:21   

from a in m.Account join ac in m.VwAccountConfirmation on a.AccountId equals ac.AccountId into acg from acgitem in acg.DefaultIfEmpty() where acgitem.AccountId == null

"acgitem.AccountId" is an int32 and its not nullable. So why is the compiler letting me compare it with null? (This query works)

acgitem.AccountId is a projected field (result of Join...Into...) that can accept null.

Example from Northwind:

var query=  from c in db.Customers
                    join o in db.Orders on c.CustomerID equals o.CustomerID into sr
                    from x in sr.DefaultIfEmpty()
                    select new {CustomerID= c.CustomerID, ContactName=c.ContactName, OrderID = x.OrderID == null ? -1 : x.OrderID}; 

Also I'm getting a code hint or something for 'acgitem.AccountId == null' that may be Resharper and it says... 'Expression is always false'. I suppose an int32 is never going to be null - is this what it means?

Just ignore the resharper hint, as it seems that it can't evalute projectioned linq code correctly.

Your code is perfectly correct.