Asked by:
Required Attribute in Model

Question
-
User1879907140 posted
I'm using EntityFrameworkCore and created models from an existing database. Several of the tables have Required columns, however, when the model was built, the [Required] attribute doesn't appear above the column name and caused the _ValidationScriptsPartail to fail, I had to add it manually.
code generated:
public partial class Cars { public int CarId { get; set;} public string CarModel { get; set;} public string SalesPerson { get; set:} }
The model and salesperson is a required field in the table, so I had to add it manually:
public partial class Cars { public int CarId { get; set;} [Required] public string CarModel { get; set;} [Required] public string SalesPerson { get; set:} }
Is there something I can run to do this automatically? I don't want to add [Required] to 40 or so fields manually.
Wednesday, June 10, 2020 8:07 PM
All replies
-
User475983607 posted
There are two different types of required. SQL has the NOT NULL constraint and MVC has input validation. These are two different things. I assume you used the Fluent API to set the SQL NOT NULL constraint. which is why you do not have the annotation on the entity properties
Usually a ViewModel is used in the UI rather than an entity but whatever you choose, Entity or ViewModel, you'll need to add the [Required] attribute to the properties you wish to apply UI validation. You might be able to scaffold the entities but I'm not sure.
Wednesday, June 10, 2020 8:21 PM -
User-474980206 posted
if not null columns have a default, then they are scaffolded as not required. if you did not supply a default, then probably, you used fluent api rather than data annotations when you scaffolded. see docs:
https://docs.microsoft.com/en-us/ef/core/managing-schemas/scaffolding?tabs=dotnet-core-cli
-- bruce
Wednesday, June 10, 2020 8:54 PM -
User1686398519 posted
Hi,GeorgeTheCoder
- EF and ASP.NET MVC are two different things. If you want to use MVC data validation, you still need to add data annotations yourself after you generate the model.
- I found an extension tool called "Huagati DBML/EDMX Tools", which can meet your needs, you can refer to this link.
Best Regards,
YihuiSun
Thursday, June 11, 2020 10:57 AM -
User-474980206 posted
The since mvc 4, it has supported data annotations in addition to its own.
Thursday, June 11, 2020 2:28 PM -
User-857013053 posted
The validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required attribute indicates that a property must have a value;
Thursday, June 11, 2020 8:58 PM