Scott Selby Scott Selby - 8 months ago 103
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
if there is no record it will return a Default Object - also thought that this default object will have a default value of
. If that is not how it works then would would be the best way to write this , wanting it to be set to
for default.

is this the best?

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


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)

Or in query syntax:

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

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.