EF model property not null without [Required]

.net-core asp.net-core-2.0 c# entity-framework entity-framework-core

Question

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?

1
3
10/24/2017 4:18:07 PM

Accepted Answer

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);
}
7
10/24/2017 7:05:32 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow