Soner Sevinc
Soner Sevinc

Reputation: 400

Linq Data Can Not Be Null By Using Stored Procedure

I tried to use a stored procedure with linq.

If result.FirstOrDefault().CustomerName is null, I get the following exception,

NullReferenceException was unhandled
Object reference not set to an instance of an object

With the following code:

var result = context.sp_CustomerInformation(CustomerId).ToList();
var MyCustomerName = result.FirstOrDefault().CustomerName;

Where did I go wrong?

Upvotes: 0

Views: 687

Answers (1)

Steven V
Steven V

Reputation: 16585

You're running into that error because FirstOrDefault() will return the default value of the type when the result has not matches. In this case, the default value is null. So you're attempting to access a property of a null object which will result in a NullReferenceException.

You need to something like:

var result = context.sp_CustomerInformation(CustomerId).ToList();
var object = result.FirstOrDefault();
var MyCustomerName = "";

if(object != null)
    MyCustomerName = object.CustomerName;
else
    // do something here if there were no results

For what it's worth you can probably combine your result query as well:

var result = context.sp_CustomerInformation(CustomerId).FirstOrDefault();

instead of ToList() which will return all matching records. FirstOrDefault will only get the first record. Then you would be able to use result instead of object from the above example.

Upvotes: 1

Related Questions