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

When you make a navigation property virtual you enable lazy loading. You've got that right. But the opposite of lazy loading is not eager loading in this case. It is "no loading unless you do the loading".

So you either have to enable lazy loading or use Include. Or do something like

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

where db is a TestDbContext instance and parent a fetched Parent object.

于 2013-02-08T22:00:29.663 に答える