What does null! do in EF CORE? [Answered]
Hi, I've used scaffold db to generate models from existing table and I noticed this interesting pattern
Keep in mind city_id must not be null so why does EF Core generate it with default value of null and what does ! mean after unll?
7 Replies
! (null-forgiving) operator - C# reference
Learn about the C# null-forgiving, or null-suppression, operator that is used to declare that an expression of a reference type isn't null.
I've read it but I still don't understand why does it set it to that when it will never be null
since it is set as not null in table
I mean from what I understand it is reverse null
meaning never null
if I'm correct ?
it's just a code specific issue. if you don't assign anything to
City
, you'll end up with the warning Non-nullable type 'City' must have a value when leaving the constructor.
so you explicitly set a value to it so you don't get that warning
at least that's how i understood it
and since you can't just set null
to it (because City
is a non-nullable type, and assigning null
to it will come up with a different warning) you just tell it to ignore the fact that it's null
maybe someone who knows EF more will correct methank you, kinda confusing but scaffold probably didn't make a mistake
You can do something like this
(which is basically the same, because
default
== null
for reference types)
but if you prefer how it looks, for sure✅ This post has been marked as answered!