I have a problem where a property of a newly added entity is not lazy-loaded, if required immediately after adding the entity.
For example:
I have a User entity with a virtual JobRole property:
public class User
{
public int Id { get; set; }
public virtual JobRole JobRole { get; set; }
public int JobRoleId { get; set; }
public string Name { get; set; }
}
I then add a new User:
public User Add(User user)
{
var addedUser = _myContext.Users.Add(user);
myContext.SaveChanges();
return addedUser;
}
The returned reference to the new User is then passed to a Razor view, where it tries to display the JobRole (eg JobRole.Name). At the point that the User is passed to the View, it has:
- JobRoleId set correctly to an integer value.
- JobRole = null
I would then expect JobRole to be lazy-loaded, when used by the View, but it isn't and results in a null-reference exception.
Is this expected behaviour, or is there a way to get newly added entities to lazy-load their properties?
Thanks in advance for any ideas.
Environment: Using Entity Framework 4.2 code-first. Lazy-loading enabled.