How to avoid dataannotation being overwritten in the EF auto-generated model
It is believed that when many people touch Ef+mvc, the DataBase first mode will be rewritten when it regenerates the model when it generates the validation information in the model class.
Here's a way to do this:
For example, I have a book class is generated from the database into model, we can create a local class name in the Models folder with the book Class (note: The namespace of the class must be associated with the automatic
Classes belong to the same namespace), the class content is empty, and then a class (Bookmetadata) is created underneath the new section class, plus the columns we need to validate and the validation letters
And then you need to
[Metadatatype(typeof (bookmetadata))] added above the new book class name
At this point we do not have to change the code in the View page. So when we re-generate the model, some of our own definition of the class book will not be affected.
Here is the sample code:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 usingSystem.ComponentModel.DataAnnotations;6 7 namespaceWeb.models8 {9[Metadatatype (typeof(Bookmetadata))]Ten Public Partial class Book One { A classBookmetadata - { -[Display (Name ="name")] the[Stringlength ( -, Minimumlength =2, errormessage ="The name cannot be greater than {2} and is less than {1}")] - Public stringName {Get;Set; } - -[Required (errormessage ="The price cannot be empty")] +[Range (5, -, errormessage ="Price between 5-100")] - Public decimalPrice {Get;Set; } + A Public decimalTime {Get;Set; } at } - } -}
Solution:
Validation of the EF DataBase first generation model