C# 尝试使计算属性与实体框架配合使用

C# 尝试使计算属性与实体框架配合使用,c#,entity-framework,C#,Entity Framework,下面是我正在使用的类的简化版本: 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; s

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

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);
    }
}
公共类父类
{
公共int Id{get;set;}
公共列表子项{get;set;}
public int ChildrenSum{get{返回Children.Sum(c=>c.Value);}
}
公营儿童
{
公共int Id{get;set;}
公共int值{get;set;}
公共父级{get;set;}
}
公共类TestDbContext:DbContext
{
公共数据库集父项{get;set;}
公共DbSet子项{get;set;}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().HasRequired(e=>e.Parent);
modelBuilder.Entity().HasMany(e=>e.Children);
}
}
公共类TestDbContextInitializer:DropCreateDatabaseAlways
{
受保护的覆盖无效种子(TestDbContext上下文)
{
var parent=new parent{Children=new List()};
parent.Children.Add(新的子项{Value=3});
parent.Children.Add(新的子项{Value=1});
parent.Children.Add(新的子项{Value=2});
context.Parents.Add(parent);
}
}

当我运行所有程序时,所有种子信息都在数据库中,但是ChildrenSum属性失败,因为没有加载子项。这是我的期望,因为我没有使导航属性虚拟化。我遗漏了什么吗?

当您将导航属性设置为虚拟时,您启用了延迟加载。你说得对。但是,在这种情况下,延迟加载的对立面不是即时加载。它是“除非您进行加载,否则不加载”

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

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

其中,
db
是一个
TestDbContext
实例,
parent
是一个获取的
parent
对象。

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

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

db.Entry(parent).Collection(p => p.Children).Load();
其中
db
TestDbContext
实例和
parent
获取的
parent
对象