I have a Person and Occupation table in my DB. When I create a Person, their default OccupationId is null.
Let's say that I created a person and their Id is 11. Also, there is an occupation, let's say Diver, and its Id is 53. I then do the following:
using (var context = new DbEntities())
{
person.OccupationId; //currently null
person.Occupation; //currently null
var person = context.People.First(x => x.Id == 11);
person.OccupationId=53;
context.SaveChanges();
var occupation = person.Occupation.Description; //Exception: Occupation is null
}
The code fails on the last line because the occupation was initially null and the new occupation didn't get lazy loaded after the save. If the person had an occupation before running this code and the old Occupation was lazy loaded, then the new Occupation would come up after the save.
In other words, if the person had an Occupation of Janitor first then this would work:
using (var context = new DbEntities())
{
var person = context.People.First(x => x.Id == 11);
var occupation = person.Occupation.Description; //this would say Janitor
person.OccupationId=53;
context.SaveChanges();
var occupation = person.Occupation.Description; //This would say Diver
}
Is there a way to lazy load the new Occupation after the save if the initial Occupation was null?