Enable Automatic Verification for Entity Framework Databases
Luo chaohui (http://kesalin.cnblogs.com /)
This article follows the "signature-non-commercial use-consistency" creation public agreement ASP. net mvc is indeed more advanced than the previous ASP programming model VIEW-BLL-DAL three layer architecture, coupled with Entity Framework tool, the development of Web applications is very easy. To combine the two, the code first mode is very easy to use, so that we can easily add many system. componentmodel. dataannotations to the model field to verify the field. However, it is a little inconvenient to use the database first mode, but there are still some solutions. Using the partial class is a solution. Example Code It demonstrates that in database first mode, two data models are used, and the partial class is used to automatically verify the fields, and the data model is encapsulated with a separate DLL. The demo result is as follows:
The data on the student and school pages above comes from two databases, and the name length verification is to add the corresponding partial class fieldSystem. componentmodel.Dataannotations.
Project Structure:
The Demo code is very simple. Here we will only list the implementation of student. CS:
Using System; Using System. componentmodel. dataannotations; Namespace Student. Dal { Public Partial Class Student {[required] [stringlength ( 8 , Errormessage = " {0} should contain at least 6 characters. " , Minimumlength = 6 )] [Display (name = " Name " )] Public String Mname { Get { Return Name ;} Set {Name = Value ;}} [required] [display (name =" Age " )] Public Int64 mage { Get { Return Age ;} Set {Age = Value ;}}}}
From the code above, we can see that the partial class encapsulates the entity class automatically generated by EF. Although there is redundancy, it is tolerated in order to achieve automatic verification. I do not know whether there is a better way to do this, provided that you do not modify the entity class automatically generated by EF.