C # linq exception: object reference not set on object instance

When I run a linq query, I only return results when the item can be found; if no elements are found, it throws an "object reference not set to an object instance" exception

How can I not throw this exception? I only want to return the result even if it is empty.

var id = db.table.Where(a => a.item == passed_item).FirstOrDefault().id;

      

+3


source to share


2 answers


This method FirstOrDefault

will return null

if the object is not found. Hence, if you try to read the value id

, then an exception will be thrown.

One way to avoid this:

// I suppose that the id you want to read is an int.
// If it isn't, please change the code correspondingly. 
int id;
// Try to get the record.
var record = db.table.Where(a => a.item == passed_item).FirstOrDefault();
// If you find the record you are looking for, then read it id.
if(record!=null)
    id=record.id;

      

Update



Another option would be to follow what DavidG

suggested in his comment:

var record = db.Table.FirstOrDefault(a => a.item == passed_item);

      

and the next step will be the same.

+12


source


var id = (from a in db.table
      where a.item == passed_item
      select a.id).FirstOrDefault();

      



This ensures that it only tries to dereference id

when something is found. Another wise, id

will be assigned regardless of the default value for the property id

(null or zero)

+1


source







All Articles