Non-Nullable type "required" double up.
Hi Guys, I'm creating a model for use with Entity Framework, VSCode is yelling at me because a property doesn't have "required", but I do have it in the square brackets above. Do these two different versions of "required" overlap? or do they genuinely serve different purposes?
18 Replies
They're different, the latter enforces that the prop be set by a constructor or object initializer.
The former,
[Required]
, is metadata read by stuff like EF. It predates the required
keyword and is not looked at by the compiler. EF only looks at [Required]
.
With that said
You have nullable-reference types on, and EF does look at that, so string
by itself implies non-null to EF. The [Required]
is redundant. @FraznoFire
If you wanted SerialNo to be nullable, you'd use string?
instead of string
.Oh so anything that doesn't have
<T>?
is practically the same as [Required]
as far as EF is concerned?Yes,
T
implies not nullable, T?
implies nullable.I reccomend you give this article a read https://learn.microsoft.com/en-us/ef/core/modeling/
Creating and Configuring a Model - EF Core
Overview of creating and configuring a Entity Framework Core model via Fluent API, Data Annotations and conventions.
Will do, thank you!
Also, I personally lean towards the fluent API for model config over the attributes.
It's more flexible, and can do everything attributes can, but attributes can't necessarily do everything the fluent api can.
So if I wanted to use attributes like
[Key]
and [DatabaseGeneratedOption...]
, there are FluentAPI options available for that as well?For keys, unless you need a compound key, it can be inferred by convention if you named the key column
Id
or FooId
(where Foo
is the table name).
But, to answer your question, yes.When the docs mention using FluentAPI by creating an override method to override the model builder, where do I put that? inside the model itself?
OnModelCreating is in the dbcontext, if that's what you mean
from the article
ah ok, I might stick with the Data Annotations for the time being because at least for me it's a bit easier to keep track of, since it's in the same place as the model itself
You can do that with fluent though. Keep reading 🙂
I can't find anything that says you can do it outside of the dbcontext
"Grouping configuration"
That looks to be a bit out of my depth for the moment, but I will keep it as a reference for the future, thanks for your help!
Actually, why does it complain about having ‘string’ without a ‘required’, but doesn’t care about other types like GUID?
wondering the same tbh. its always string
Guid is a value type
Guid is a value type (if you at the docs you’ll see it’s a struct, not a class) and value types cannot be null without the ? stuff. Their default value is the zero value.