Entity Framework Tutorial Basics (+): Validate entity

Source: Internet
Author: User

Validate Entity

You can write the custom server side validation for any entity. To accomplish this, override validateentity method of DBContext as shown below.

protected OverrideSystem.Data.Entity.Validation.DbEntityValidationResult validateentity (Dbentityentry entityentry, system.collections.generic.idictionary<Object,Object>items) {    if(entityentry.entity isStudent) {        if(entityentry.currentvalues.getvalue<string> ("Studentname") =="")        {            varList =NewList<system.data.entity.validation.dbvalidationerror>(); List. ADD (NewSystem.Data.Entity.Validation.DbValidationError ("Studentname","Studentname is required")); return NewSystem.Data.Entity.Validation.DbEntityValidationResult (entityentry, list); }    }    return Base. Validateentity (entityentry, items);}

As can see in the above code, we is validating the Student entity. If Studentname is blank, then we were adding dbvalidationerror into Dbentityvalidationresult. So whenever the Dbcontext.savechanges method and you try to save Student entity without studentname, then it'll thr ow dbentityvalidationexception. For example:

Try{    using(varCTX =Newschooldbentities ()) {ctx. Students.add (NewStudent () {studentname ="" }); CTx. Standards.add (NewStandard () {StandardName ="" }); CTx.    SaveChanges (); }}Catch(dbentityvalidationexception dbex) {foreach(Dbentityvalidationresult Entityerrinchdbex.entityvalidationerrors) {foreach(Dbvalidationerror Errorinchentityerr.validationerrors) {Console.WriteLine ("Error property Name {0}: Error Message: {1}", error. PropertyName, error.        ErrorMessage); }    }}

Entity Framework Tutorial Basics (+): Validate entity

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.