I found out that, if i set a navigation property as required ( using the Required attribute ) and use lazy-loading proxies, when i load the parent entity and do nothing but try to save in the same context, an EntityValidationError occurs which is like "xxx field is required".
With hibernate in Java and NHibernate in .NET, it is possible to just fetch an entity without its navigation properties ( all lazy loaded ) , update it and save again. The framework realizes that nothing changed with the navigation references and do not throw any errors.
The example is below
[Table("Address")]
public class Address
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddressId { get; set; }
[Required, StringLength(512)]
public virtual string AddressLine1 { get; set; }
}
[Table("User")]
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
public string Name {get; set;}
[Required]
public virtual Address Address {get; set;}
}
void LoadAndSaveUser() {
var user = Context.Users.First();
user.Name = "foo";
// if i comment out this line
// ( probably EF fetches the lazy loaded entiy )
// the code works. it is strange though because i don't access any property/method of the Address
// var dummy = user.Address
Context.SaveChanges();
}
When i try this without the "Required" attribute on the Address property, no error occurs. With the Required attribute, i get "Address field is required!". Since each user should have an address, i want the attribute to create a consistent model.
In some forums, i found posts suggesting to include the navigation property while loading the parent entity ( eager load in other words ) but it is not a feasible approach if we have too many navigation properties.
Am i doing something wrong or is there any other way to implement such funcionality ?