One Entity Framework ‘gotcha’ I keep encountering is that lazy loading is turned off for validation. So if I load an entity using db.Find() , then update it and attempt to call db.SaveChanges() (with db being the DBContext object) an error will be thrown if the entity has any related entities marked as [Required].
As I see it there are three ways to handle this –
1. Not mark the related entity as [Required] and manually ensure it is present at the time of creation
2. Use Include() when loading the entity to include the related entities
3. Perform custom validation.
I am tending towards using (1) due to its simplicity.
Are there any suggestions or patterns that users employ for this scenario?
There are two more options:
Define that the relationship is required in Fluent API instead of using the
[Required]attribute:Expose a non-nullable foreign key in your model, then you don’t need the
[Required]attribute (and mapping with Fluent API neither) as conventions will detect that the relationship is required:Honestly, I don’t know why it works. It looks that in this case for some reason the EF validation only checks the data annotations, and not the Fluent configuration, although the represented model, the relationship and the database schema are the same in all cases.