none
problem with linq select and nullable columns that contain relationship ids RRS feed

  • Question

  • ok .. so here is my problem:

    lets say i've two tables:
    customer(id,idTown,Name)
    town(id,Name)

    and idTown is an int?.

    the visualstudio wizard (linq to sql classes) created a datacontext for me.

    i made i query to fill an "IEnumerable<customer> ienum_customers" with data.

    now i want to run another query agaist ienum_customers.

    my query looks like that:

    var customers = c from ienum_customers
                             select new {
                                 c.Name,
                                 Town = c.town.Name <<< here is the nullable problem
                             }

    and the exception is: object reference not set to an instance of an object because idTown can have no value at all.
    if there is a value no problem occures.

    any idea what a correct solution would be?
    Monday, September 21, 2009 12:23 PM

Answers

  • Could you use an inline if to assign the value to Town?

    Something like:

    Town = c.town != null ? c.Town.Name : "N/A"

    We have used inline if statements when writing selects like this, although ours have usually involved a left join.
    • Proposed as answer by jonesri Monday, September 21, 2009 2:36 PM
    • Marked as answer by Zhipeng Lee Monday, September 28, 2009 1:22 AM
    Monday, September 21, 2009 2:32 PM