0. A question
People who have used EF believe they will encounter validation failed for one or more entities. See ' entityvalidationerrors ' This exception, which is due to an exception caused by EF validating the entity before writing to the database (if configuration is not set. Validateonsaveenabled=false words), because EF did not throw this exception details to the upper layer, often can not track to which property is not verified through, although know wrong, but the vegetarian still do not know where the wrong ah, how to change?
1. Record Entityvalidationerrors in DbContext
Now that you have EF eating entityvalidationerrors, I have to let it come back, first. 22 Code:
Public classTestdbcontext:dbcontext { Public Override intSaveChanges () {Try { return Base. SaveChanges (); } Catch(Dbentityvalidationexception exception) {varErrormessages =exception. Entityvalidationerrors. SelectMany (Validationresult=validationresult.validationerrors). Select (M=m.errormessage); varFullerrormessage =string. Join (", ", errormessages); //Record Log//Log.error (fullerrormessage); varExceptionmessage =string. Concat (Exception. Message,"Verify that the exception message is:", Fullerrormessage); Throw Newdbentityvalidationexception (Exceptionmessage, exception. Entityvalidationerrors); } //other exceptions throw to the top } }
Quite halal a few lines of code can get EF verification message, very cost-effective wood!
In the EF additions and deletions, the underlying enabling entity validation and logging is very necessary, especially the code to the line, if there is no log, the system is abnormal, simply can't start ...
To record entityvalidationerrors details