tags:

views:

51

answers:

1

This is a weird one that i can't figure out.

My method has one paramemer a nullable int

int? selectedtitleid

This is the Linq code:

var titles = from t in dc.Titles
            select new SelectListItem 
            { 
                Text = t.Title1, 
                Value = t.TitleID.ToString(), 
                Selected = (t.TitleID == selectedtitleid)
            };

return titles.ToList(); // Error gets thrown here

It works fine when selectedtitleid is not null - but throws an exception when it is null.

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

I did a test which was something like this

int? t1 = null;
bool b1 = (t1 == null);

And b1 gets set to false - so why doesn't this happen in the Linq query ?

It's probably something simple - so anyone any ideas ?

Cheers

+1  A: 

OK, the LINQ query you provided will transfer to SQL syntax like:

SELECT 
    [t0].[Title1],
    [t0].[TitleID],
    (CASE 
        WHEN [t0].[TitleID] = @p1 THEN 1
        WHEN NOT ([t0].[TitleID] = @p1) THEN 0
        ELSE NULL
     END) AS [Value]
FROM [dbo].[Titles] AS [t0]

where @p1 is actually your selectedtitleid variable.

Now imagine that selectedtitleid = null. This means nor the first condition, not the second in the CASE block won't be fulfilled. This is because null value in SQL (null is not equal to any other value even null). So when the selectedtitleid value is null, null value for the [Value] field will be returned. That is why you get your exception.

The workaround is to change your code:

var titles = from t in dc.Titles
            select new SelectListItem 
            { 
                Text = t.Title1, 
                Value = t.TitleID.ToString(), 
                Selected = ((t.TitleID ?? 0) == (selectedtitleid ?? 0))
            };

This means that insted of null there will be integers comparison. So if t.TitleID is null and selectedtitleid is null, Selected will be set to true.

Alex
Ahhh good man - that's perfect :) I actually tried doing (t.TitleID == selectedtitleid) ?? false - but because it's changing it to SQL it didn't work :) Cheers Alex
IrishJoker