views:

428

answers:

1

I am trying to set a unique identifier in my customer table from the unique identifer from my membership table (asp.net membership).

However I am getting a null reference exception when doing so. This is the code.

 Customer customer = db.Customers.SingleOrDefault(c => c.Id == Convert.ToInt32(formValues["CustomerId"]));
 Guid userId = new Guid(user.ProviderUserKey.ToString());
 customer.UserId = userId;

It crashes on the last line.

I have tried different settings in my Customer table on the database and in the LINQ to SQL model but I keep getting this.

Anyone know why?

Thanks

+2  A: 

You are seeing this because this expression:

db.Customers.SingleOrDefault(
    c => c.Id == Convert.ToInt32(formValues["CustomerId"]));

is returning null and that null is being assigned to the customer variable. When you use customer two lines later it is throwing the NullReferenceException.

The best thing to do here is to debug this code and see what formValues["CustomerId"] is set to - most likely this value is not set which is causing you to look up a customer in the database for a CustomerId that doesn't exist.

Andrew Hare
+1 yup - basic principle of defensive programming: if anything can return NULL (and .SingleOrDefault() definitely can!), you must **ALWAYS** check for NULL !
marc_s
I feel silly :( I had the customer Id as a hidden field but it wasn't within the Begin Form using block. Anyway thanks.
dean nolan