Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework Code First update error with unloaded required navigation property
    primarykey
    data
    text
    <p>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". </p> <p>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. </p> <p>The example is below</p> <pre><code>[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(); } </code></pre> <p>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.</p> <p>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. </p> <p>Am i doing something wrong or is there any other way to implement such funcionality ?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload