c# - Object Reference Error - Linq -


i new linq , entity framework, , receiving null reference exception on query:

using (var db = new phoenixcontext()) {     tblcustomer cust = (from c in db.tblcustomer                         c.customerid == _customerid                         select c).firstordefault();      string altphone;     altphone = cust.tblcustomercontactinformation1.tblcustomercontactinformationphone.where(p => p.phonetypeid == 2).firstordefault().phone; ) 

there single row in tblcustomercontactinformationphone. clause should remove it, , should end getting empty string. however, instead receive:

object reference not set instance of object. 

what doing wrong, , how do correctly empty result set converted empty string?

the linked question not helpful, specific use of linq, question not cover. @evanmcdonnal's answer quite helpful, , solved problem.

this going closed because question duplicates 1000000000000 other nullreferenceexception questions have been asked before.

think .where(p => p.phonetypeid == 2).firstordefault().phone

what happens when there no item in tblcustomercontactinformationphone phonetypeid of 2? firstordefault gives 'default' in case null , thevalueretuendfromfirstordefaultwhichisnull.phone , nullreferenceexception.

instead break 2 lines.

string phone = string.empty; var temp = cust.tblcustomercontactinformation1.tblcustomercontactinformationphone.where(p => p.phonetypeid == 2).firstordefault();  if (temp != null)     phone = temp.phone; 

edit: option use select value of phone can use null coalescing operator you're trying to. this;

var phone = cust.tblcustomercontactinformation1.tblcustomercontactinformationphone.where(p => p.phonetypeid == 2).select(x => x.phone).firstordefault() ?? string.empty; 

this works fine because lambda expression in select applied 0 elements if none returned end getting null firstordefault in case you'll take empty string.