Scott Selby Scott Selby - 1 month ago 6
C# Question

linq to sql Object Reference not set to an object

I have this query in Linq to Sql

decimal Rewards = db.User.FirstOrDefault(x => x.FFUserID == UserID).TotalCommission;


This query didn't find a record matching the userID , so obviously that's why the exception is being thrown. My question is - I thought that by using
.FirstOrDefault()
if there is no record it will return a Default Object - also thought that this default object will have a default value of
0.0M
for
TotalCommission
. If that is not how it works then would would be the best way to write this , wanting it to be set to
0.0M
for default.

is this the best?

decimal Rewards = db.User.FirstOrDefault(x => x.FFUserID == UserID)
.TotalCommission ?? 0.0M

Answer

FirstOrDefault will return null when no item is found. So when you access the TotalCommission property, there's a chance of a NullReferenceException. I think you want to do this:

decimal Rewards = db.User.Where(x => x.FFUserID == UserID)
                         .Select(x => x.TotalCommission)
                         .FirstOrDefault();

Or in query syntax:

decimal Rewards =
    (from x in db.User
     where x.FFUserID == UserID
     select x.TotalCommission)
    .FirstOrDefault();

UPDATE: As of C# 6.0, you can now use the null-conditional operators to do something very similar to what you originally intended:

decimal Rewards = db.User.FirstOrDefault(x => x.FFUserID == UserID)
                        ?.TotalCommission ?? 0.0M

The ?. here will safely handle cases where given user ID is not found in the database and return a (decimal?)null. The plain old null-coalescing operator, ?? 0.0M, will give you the default value you expect.