Reputation: 6518
If I have defined next in map file (1-to-Many relationship between Units and Machines):
this.HasRequired(t => t.Unit)
.WithMany(t => t.Machines)
.HasForeignKey(d => d.UnitId);
When I add new entity, Machine.UnitOfMeasurement = null, sp why does DbContext return no validation problem when calling GetValidationErrors and what can I do to detect them. If I allow EF to try to update, it will return meaningless message to user, like foreign key reference error, while I can extract meaningful information to user from DbEntityValidationResult (ex property name that issued a validation error).
I am using IDataErrorInfo for validation rules, not Attributes.
Upvotes: 0
Views: 421
Reputation: 31610
EF validation does not validate navigation properties. The reason for this is that a navigation property may be null not because a related entity does not exist but because lazy loading is enabled and the related entity is just not loaded. Also, even if the navigation property is null you might have set the corresponding foreign key property which basically means that relation exists but the navigation property has not been updated yet. Also note that forcing loading related entities would mean that validation brings your entire database to memory (after loading related entities they will be validated what would result in loading related entities of newly loaded entities and so on) - you don't want this to happen (EF actually turns off lazy loading during validation to prevent from this). EF Validation does not support IDataErrorInfo - only validation attributes and IValidatableObject.
Upvotes: 1