When using the nullable-enable feature in Entity Framework Core model classes, the compiler will emit a lot of CS8618 warning like that:
warning CS8618: Non-nullable property 'Title' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
Starting with C# 11, the new required
modifier can be used (and no other workarounds are necessary) to get rid of the warnings:
class Book
{
public int BookId { get; set; }
public required string Title { get; set; } // <-- new required modifier
public decimal Price { get; set; }
}
Now, my question is:
Should all properties get the new required
modifier, even the value types?
In the example above, should Price
also get the required
modifier? Because actually, you never want the price to be 0 by default, but you always want it to be explicitely specified.
Should it be:
class Book
{
public int BookId { get; set; }
public required string Title { get; set; }
public required decimal Price { get; set; }
}
If yes, then is it correct that the database id (here BookId
) should NOT be required
because it is generated only by the database in some cases?