Search code examples
c#linqlinq-to-sql

Is there anyway anonymous joins using linq may be performed when one of the datatypes is nullable and the other isn't?


If this question has already been asked then please direct me to the SO link so I may avoid a dupe. But I wasn't able to find anything that directly answered the question.

I have the following scenario

var result = (from a in table1
                join b in table2
                  on a.column equals b.column
                join c in table3
                  on b.column equals c.column
                join d in table4
                  on new { a.column2, c.column2 } 
                     equals { d.column3, d.column6 } 
             select a);

The problem is that column2 of table3 and column6 of table4 are both of type int but 1 is nullable and the other isn't which results in "type of one of the expressions in the join clause is incorrect"

I understand the error but my question; is there any way around this? Or am I just at a dead end attempting to achieve the result I need using linq?

I've attempted to make the join work by using the Value attribute of the nullable type but that doesn't work. If there is no other recourse to achieve this using linq then I'll have to move all the code to SQL in a SPROC which I'd prefer not to do.

I have noted that I can perform the join outside of the anonymous declarations and linq has no issues with it; but I need a composite join.

Thanks


Solution

  • You need to give the properties in the anonymous type labels and the labels must be the same. Then, you can cast the non-nullable int to a nullable int.

    var result = (from a in table1
                    join b in table2
                      on a.column equals b.column
                    join c in table3
                      on b.column equals c.column
                    join d in table4
                      on new { JoinColumn1 = a.column2, JoinColumn2 = (int?)c.column2 } 
                         equals { JoinColumn1 = d.column3, JoinColumn2 = d.column6 } 
                 select a);