質問

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