0

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?

7
  • please post an example SQL query showing the company getting filled in as null when there's no rows in the result. Commented Apr 24, 2014 at 19:49
  • @Jasmine: It would take me a while to get that in SQL. I have never seen any type of null-reference error in SQL Server. Are you suggesting they can exist? Commented Apr 24, 2014 at 19:53
  • No I'm suggesting that it doesn't exist. A result with no rows doesn't return any values for any columns, so it's incorrect to say that "company" would be null after such a query. Thus, EF is handling it correctly - it is preventing you from obtaining a value from a meaningless query result. If you want to have a default value, you must provide it - which IMO, is the correct behavior. Hamlet's answer below is correct Commented Apr 24, 2014 at 20:04
  • @Jasmine: You can have a calculated column that uses this type of expression, and it's possible that since there are no matching rows in the expression, the column becomes null. Commented Apr 24, 2014 at 20:07
  • No it doesn't. Even with a calculated column, aggregate expression, or column-with-default, you still get nothing if the query returns zero rows, unless what you mean by calculated column is "we provided a value for the zero-row situation" in which case that's Hamlet's answer. If you are talking about the situation where an expression is selected as part of a row, and one of the operands of that expression is null, but the output is non-null - that's a database setting or a characteristic of the expression itself. Try select null + 'someString' on your server to find out what your setting is Commented Apr 24, 2014 at 20:20

1 Answer 1

3

You can use something like this:

let company = pc.Contact.CompaniesContacts.FirstOrDefault() != null
             ? pc.Contact.CompaniesContacts.FirstOrDefault().Company
             : null
Sign up to request clarification or add additional context in comments.

2 Comments

Gawd, I hope the SQL version of that would be more efficient than the C# version.
If you will provide the query maybe would be more efficient way to achieve what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.