Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF model property not null without [Required]

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?

like image 476
Gustav Avatar asked Dec 11 '22 09:12

Gustav


2 Answers

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);
}
like image 111
Salah Akbari Avatar answered Dec 14 '22 19:12

Salah Akbari


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.

like image 26
Anthony Giretti Avatar answered Dec 14 '22 18:12

Anthony Giretti