C
C#2y ago
barcode

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
public City City { get; set; } = null!;
public City City { get; set; } = null!;
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
ero
ero2y ago
! (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.
barcode
barcode2y ago
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 ?
ero
ero2y ago
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 me
barcode
barcode2y ago
thank you, kinda confusing but scaffold probably didn't make a mistake
SwaggerLife
SwaggerLife2y ago
You can do something like this
public City City { get; set; } = default!;
public City City { get; set; } = default!;
ero
ero2y ago
(which is basically the same, because default == null for reference types) but if you prefer how it looks, for sure
Accord
Accord2y ago
✅ This post has been marked as answered!