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?

有帮助吗?

解决方案

You can use something like this:

let company = pc.Contact.CompaniesContacts.FirstOrDefault() != null
             ? pc.Contact.CompaniesContacts.FirstOrDefault().Company
             : null
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top