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.
Solution:
Description: MODEL1.EDMX is generated by EF, Book.cs I added, the code is as follows
Model Code:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using system.web; 5 using S Ystem. Componentmodel.dataannotations; 6 7 Namespace{9 [Metadatatype (typeof(bookmetadata))]10 public partial class { class {]15 [Display (name = "Names")] [Required (errormessage = "name cannot be null")]
public string name {get; set;} [Required (errormessage = "Price cannot be empty")]19 [Range (5, errormessage = "Price 5-100")]20 public decimal Prices { Get Set;} Public decimal time {get; set }25}
Controller code:
The Add method code for BookController.cs in controllers is as follows
Public ActionResult Add () { return View (); } [HttpPost] Public ActionResult ADD (book model) { if (modelstate.isvalid) { db. Book.addobject (model); int res = db. SaveChanges (); viewdata["Status" = "success:" + DateTime.Now.ToString ();} else {viewdata["status"] = "failed:" + DateTime.Now.To String (); } return View ();}
Operating effect:
test Environment: Vs2010+.net4.0+mvc4+ef4
Validation of the EF DataBase first generation model