Validation of the EF DataBase first generation model

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.