开发者

EF4.1 Include doesn't work if you instantiate non-list association property in constructor

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 ICollec开发者_如何学运维tion<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:

  • EF 4.1 Code First: Why is EF not setting this navigation property?
  • What would cause the Entity Framework to save an unloaded (but lazy loadable) reference over existing data?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜