Is it possible to have Entity framework generate a table, from a model, with the column marked as not null without using the [Required]
annotation on the model's property?
Reason:
The object is posted to an api and I check ModelState.IsValid
in the controller. The property is supposed to be generated server side and not come from outside, but if I have the property [Required]
the ModelState.IsValid
is false (in which case I return with a BadRequest(ModelState);
).
Can I tell EF to make the column not null in some other way?
I guess another solution would be to expect another object(some sort of DTO) to be sent to the api and then do a mapping. But that object would look exactly the same save for this single property, which makes it seem a bit unnecessary, right?
Use Fluent API and IsRequired
method in your DbContext
class like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<YourEntity>().Property(t => t.YourProperty).IsRequired();
base.OnModelCreating(modelBuilder);
}
If I were you I would not use Entity Framework's entities directly, I would use a DTO first and map it into a EF Entity, why? Because your DTO and EF Entity have not the same responsibility.
DTO : Data transfer object, so just use it to transfer data EF Entity : it's the model binding to your database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With