C
C#12mo ago
Bric

Include child of nullable in EF Core

Hi, I want an Activity which has a nullable HeaderGroupId in the db. After scaffolding the db to my project with ef core scaffold command, both the HeaderGroupId and the HeaderGroup of Activity are nullable (marked with ?). I'm okay with that, but when I want to include a child of this nullable HeaderGroup I get a warning and I don't understand how I'm supposed to avoid it. What's the correct approach?
No description
7 Replies
Joschi
Joschi12mo ago
What's the warning?
Bric
BricOP12mo ago
Sorry I wasn't clear, dereference of a possibly null reference on the "h" in my lambda of ThenInclude
Joschi
Joschi12mo ago
As you said it is marked as nullable and thus the analyzer assumes, that it may be null unless you specifically check for it. If that relationship is not required, it could actually be null even if you include it. And even if it is required I'm not sure if the analyser is smart enough to understand it, if that is the case you could probably safely suppress / ignore the warning at that point. But maybe someone here with more EFCore experience has an idea, I just started out with that myself
Bric
BricOP12mo ago
I understand why it happens, and yes technically if my activity does not contain a headerGroup calling headerGroup.Headers will throw a NRE. I wish I could include (or in this case, ThenInclude) with a condition
dreadfullydistinct
There is an open ef core issue about this https://github.com/dotnet/efcore/issues/21663
GitHub
Create DiagnosticSuppressor for CS8602 in Linq expressions and Incl...
Currently CS8602 (Dereference of possibly null reference) is triggered for nullable properties in linq expressions, even though no NRE possible when query is executed on DB side. Example 1 (Linq): ...
dreadfullydistinct
My understanding is that the potential null reference exception it is warning you about will never actually happen, because that expression tree is compiled to SQL and run on the DB Personally I use the null forgiving ! operator to get rid of them where I know that it will be evaluated by the db
Bric
BricOP12mo ago
Thanks for the clarification!
Want results from more Discord servers?
Add your server