Replies: 1 comment
-
Closing in favor of #867 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi team,
I'd like to discuss the use of null-conditional operators
?.
inIQueryable
projections. While null-conditional operators are generally useful, I believe they can introduce unnecessary complexity and potential runtime issues when used withIQueryable
projections.Consider the following code snippet:
This code will generate the following lambda expression:
IQueryables
are typically translated into SQL statements before being executed, rather than being compiled and run directly in the .NET runtime. This means that the?.
method doesn't do anything useful in this context.However, if you are mapping objects to memory rather than projecting an
IQueryable
, the?.
operator can be useful.If you change the Products property in Category to the following:
Then the generated codes changes as following:
While both generated codes produce the desired output in this straightforward scenario, the first approach generates a more complex lambda expression tree without a clear justification. When dealing with more intricate situations, such as dynamic queries like OData, only the second approach yields a valid solution.
I understand your intention to adhere to C# 8 nullable reference types, and I commend your efforts. However, if I were to construct the query manually, I would follow the same pattern for the second scenario while opting for the following simplified approach for the first one:
By employing the
!
operator, we can safeguard against C# compiler warnings that might arise from this code. Moreover, the likelihood of encountering null reference exceptions is minimal. Additionally, it leads to lambda expression as streamlined as possible because!
has no side effect on the lambda expression.Certain legacy IQueryable providers like EF6 may encounter difficulties with the
?
operator in certain scenarios, even without the presence of OData or other complexities. Therefore, I strongly recommend utilizing the!
operator for projections involving nullable reference types.With kind regards
Beta Was this translation helpful? Give feedback.
All reactions