Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent EF from validating properties that are not mapped during DBContext.SaveChanges()

I have a user model with two [NotMapped] string properties Password and ConfirmPassword. These are unmapped because I save password as byte array (after salting) so there are two additional properties (mapped) InternalPassword and Salt in user model.

The problem is when I use the user model to change password, entity framework throws DBEntityValidation error stating "The Password property is required." What I understand here is that EF is trying to validate my model before saving and since Password/ConfirmPassword are not set, it is throwing this error. This raises following questions:

1) If property Password is explicitly annitated as [NotMapped], why is EF validating it during save? 2) IF EF performs validation during save, and the same is also performed during binding (I.E. in the controller action method), does it not hurt performance? (validating twice) 3) What's the recommended way to resolve this error? (If I explicitly set Password property to dummy value, error is gone.)

Edit: I've removed the code since it is lengthy and may be the cause of no answer yet. If somebody wants to have a look, I can append it below.

like image 582
Varun K Avatar asked Aug 13 '11 15:08

Varun K


1 Answers

Automatic validation in EF is somehow strange feature - I don't like it. You can read this article to find some information how to validate just selected properties but I expect you must trigger that validation manually and turn off global validation by calling:

context.Configuration.ValidateOnSaveEnabled = false;

Your problem with NonMappedAttribute is interesting. I didn't go deep into implementation of validation in EFv4.1 but if the implementation is build around the same rules as common validation based on data annotations, it uses only attributes derived from ValidationAttribute - NotMappedAttribute is not derived from ValidationAttribute.

That is another problem of such implementation - it combines mapping definition and validation but these two features are not the same and should not be implemented by the same API.

@alun deleted his answer - the valid answer to your question. Your validation belongs to view model dependent on the operation a user is performing. It doesn't belong to persistence model. Why? Exactly because of your current issue - persistence model can hold only single validation set and every operation in your application must ensure that validation criteria for that set are met = you must ensure that Password and ConfirmPassword are filled even if your current operation doesn't demand it => problem.

like image 117
Ladislav Mrnka Avatar answered Sep 28 '22 12:09

Ladislav Mrnka