I have some simple Code First classes with a Many to One relationship. If I retrieve a Child and use Include to retrieve the School, then it works OK if I comment out the School = new School() line, but with it in, the School class is not populated. I assume that this is expected behaviour (can someone confirm?), but it caught me out, especially given that doing the same with a collection property works fine.
public class Child
{
public Child()
{
School = new School();
}
public int Id { get; set; }
public string Name { get; set; }
public int SchoolId { get; set; }
public School School { get; set; }
}
public class School
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Child> Children { get; set; }
}
public class TestContext : DbContext
{
public TestContext(string connectionString)
: base(connectionString)
{
}
public DbSet<Child> Children { get; set; }
}
public class Test
{
public Test()
{
var context = new TestContext("...connectionstring...");
var child = context.Children.Include(x => x.School).Where(x => x.Id == 1).SingleOrDefault();
Debug.Assert(child.School.Id != 0, "School is null");
}
}
Yes, instantiating reference navigation properties in the default constructur causes trouble:
It works fine for collections because you are just instantiating an empty collection in this case but not any referenced objects. But you better avoid to do this for a reference property.