Вопрос

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