In a nutshell: Entity Framework Code First (EFCF) validation does not load lazy properties. If any of these properties is marked as required, and it is not loaded, a validation error will occur.
While I understand the reason – imagine you are saving lots of entities where a required property is not loaded, this will cause lots of accesses to the database just for checking that the required entity exists – I think the way things are is not very productive. I hope the Entity Framework team can come up with a solution, I’ll probably propose something myself.
Imagine you have a class model such as:
Say you load a child and make some change:
This will throw a DbEntityValidationException, because EFCF will think that the Child instance does not have its Parent property set. This is really annoying and is the source of great frustration.
Of course, there are some workarounds:
- Explicitly force loading all lazy loaded properties before calling SaveChanges;
- Include all lazy loaded properties in the query (best option), such as:
- Disable validation at all (not recommended):
- Disable lazy loading globally (also not recommended):
- Finally, you can remove the required constraint (not good as well):