1

这是我正在使用的类的简化版本:

public class Parent
{
    public int Id { get; set; }
    public List<Child> Children { get; set; }
    public int ChildrenSum { get { return Children.Sum(c => c.Value); } }
}

public class Child
{
    public int Id { get; set; }
    public int Value { get; set; }
    public Parent Parent { get; set; }
}

public class TestDbContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>().HasRequired(e => e.Parent);
        modelBuilder.Entity<Parent>().HasMany(e => e.Children);
    }
}

public class TestDbContextInitializer : DropCreateDatabaseAlways<TestDbContext>
{
    protected override void Seed(TestDbContext context)
    {
        var parent = new Parent { Children = new List<Child>() };
        parent.Children.Add(new Child { Value = 3 });
        parent.Children.Add(new Child { Value = 1 });
        parent.Children.Add(new Child { Value = 2 });
        context.Parents.Add(parent);
    }
}

当我让一切运行时,所有种子信息都在数据库中,但是 ChildrenSum 属性失败,因为孩子们没有被急切地加载。这是我的期望,因为我没有将导航属性设为虚拟。我错过了什么吗?

4

1 回答 1

4

当您创建导航属性时virtual,您会启用延迟加载。你说得对。但在这种情况下,延迟加载的反面不是急切加载。它是“除非进行加载,否则不会加载”。

因此,您要么必须启用延迟加载,要么使用Include. 或者做类似的事情

db.Entry(parent).Collection(p => p.Children).Load();

wheredb是一个TestDbContext实例和parent一个获取的Parent对象。

于 2013-02-08T22:00:29.663 回答