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; 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 属性失败了,因为 children 没有被急切加载。这是我的期望,因为我没有将导航属性虚拟化。我错过了什么吗?

最佳答案

当您将导航属性设置为虚拟 时,您将启用延迟加载。你说得对。但在这种情况下,延迟加载的反面并不是急切加载。它是“没有加载,除非加载”。

所以你要么必须启用延迟加载,要么使用 Include .或者做类似的事情

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

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

关于c# - 尝试使计算属性与 Entity Framework 配合得很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14780821/

相关文章:

c# - 使用C#读取RAR文件的内容

c# - 如何防止 SqlConnection 上的时区转换?

c# - Entity Framework :Why the collection type of entity class need to be instanced in the default constructor?

c# - Entity Framework 中的反向属性和外键有什么区别?

entity-framework - 首先防止 Entity Framework 数据库中的小数舍入

c# - 如何将 SUM 聚合函数添加到 Entity Framework 查询中

javascript - 设置textarea显示:none loses the value when trying to save

C# 屏蔽文本框

c# - 绑定(bind)的默认 ValueConverter

entity-framework - Entity Framework 6,我应该使用存储库模式吗?