Null value causing exception in LINQ's left outer join RRS feed

  • Question

  • Hi,

    Using left join in a LINQ, If I include an int column in a select new clause (Inv.CUS_CODE) in this example, it generates following error for null CUS_CODE values (placeholders):

    InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

    If I convert the null CUS_CODE to 0 using ternary operator it works fine. But my problem is I have lot of columns in different tables like that case. Do I have to convert the null values to empty placeholders for every such column? Or can we provide any modification in the give LINQ statement to handle this scenario.

    I am testing in LINQPad.


    from acc in IS_ACC_ACCOUNTs
    				   join Inv in SHMA_CUS_CUSTOMERs
    				   on acc.CUS_CODE equals Inv.CUS_CODE into DefAcc
    				   from Inv in DefAcc.DefaultIfEmpty()
    				   select new
    <strong>					   Inv.CUS_CODE // This column is of int type, defined as not null in the db</strong>


    Paradise lies at the feet of thy mother. - Prophet Mohammed (PBUH) (skype:
    • Edited by Khadim Ali Tuesday, January 31, 2012 12:18 PM
    Tuesday, January 31, 2012 12:18 PM


  • Hi Al .Net;

    The error is most likely happening when you assign that value to a variable in your code that is not nullable. You can use the ternary operator or when you assign it to a variable make sure they are being assigned to a nullable type such as int? double? and so on. I would suggest using the ternary operator so that you do not have to test the nullable types for values.


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Marked as answer by Khadim Ali Wednesday, February 1, 2012 8:19 PM
    Tuesday, January 31, 2012 4:26 PM