This seems to be a pretty strange behavior of CodeFirst,
I got a table:
public string Name {get;set;}
[Required]
public virtual Table1 Table1 {get;set;}
[Required]
public virtual Table2 Table2 {get;set;}
[Required]
public virtual Table3 Table3 {get;set;}
Now if i get a row from the database like this:
var row = database.Include("Table1").First();
row.name = "New name";
row.Table1.name = "New name";
database.SaveChanges();
it will throw 2 errors:
Table2 : The Table2 field is required.
Table3 : The Table3 field is required.
Question is, Why does it validate those 2 non-loaded non-used references?
I would prefer not to load the ENTIRE entity, as some entities can have a lot of references, to just update 1 field.
If you mark anything with
Requiredattribute it is required to exist when saving changes. EF always validates whole entity during saving and navigation properties are handled in the same way as normal properties => null = exception. Validation also doesn’t trigger lazy loading by design.Your options are:
Requiredattribute be either