How to prevent EF from validating properties that are not mapped during DBContext.SaveChanges()
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.