Question

I have an Entity Framework query that contains the following line.

let company = pc.Contact.CompaniesContacts.FirstOrDefault().Company

If you do something like this directly in SQL and FirstOrDefault() returns null, then the result of the entire expression will be null. (I.e., company will be null.)

But in Entity Framework, if the FirstOrDefault() returns null, then I get a null-reference exception.

Is there any way to have Entity Framework behave more like SQL here?

Was it helpful?

Solution

You can use something like this:

let company = pc.Contact.CompaniesContacts.FirstOrDefault() != null
             ? pc.Contact.CompaniesContacts.FirstOrDefault().Company
             : null
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top