Here’s a simplified version of the classes I’m working with:
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);
}
}
When I get everything running, all the seed info is in the database, but the ChildrenSum property fails out because the children aren’t being eager loaded. It was my expectation that they would be, since I didn’t make the navigation properties virtual. Am I missing something?
When you make a navigation property
virtualyou 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 likewhere
dbis aTestDbContextinstance andparenta fetchedParentobject.