【问题标题】:Loading grandchild object in child collection, EF [duplicate]在子集合中加载孙对象,EF [重复]
【发布时间】:2015-09-30 16:51:25
【问题描述】:

型号:

    public class Parent
    {
        public int Id { get; set; }
        public ICollection<Child> Children { get; set; }
    }

    public class Child
    {
        public int Id { get; set; }
        public int IdGrandChild { get; set; }
        public virtual Grandchild Grandchild { get; set; }
    }

    public class Grandchild
    {
        public int Id { get; set; }
    }

我有一个带有 Children 集合的现有 Parent 实体。经过一些操作后,我想像这样将新添加的子对象从数据库加载到父集合中

_context.Entry(parent).Collection(f => f.Children).Load();

但是当我这样做时,每个新添加的集合元素中的 Grandchild 对象都是空的。我也尝试以这种方式包含孙子,但孙子对象仍然为空。

_context.Entry(parent).Collection(f => f.Children).Query().Include(c => c.Grandchild).Load();

如何正确地将新项目加载到 Parent's Children 集合中,包括 Grandchild 对象?

编辑: 我不知道为什么这个问题被标记为重复? 我的问题是:我已经在一个上下文实例(表单)中有现有(加载/跟踪)父实体,然后在另一个上下文实例(表单)中我修改了实体子集合(添加或删除子)。最后,我想使用以前编写的方法之一将这些新添加的条目加载到第一个上下文实例中的父实体集合,但之后加载了新添加的对象,但它们的孙子对象为空。 我不知道如何正确地将这些新的子对象加载到存在(跟踪)的父实体而不得到空值。

【问题讨论】:

标签: c# entity-framework


【解决方案1】:

我通常使用以下(无负载)

Parent parent = _context.Parent.Include(p => p.Children.Grandchild).FirstOrDefault();

如果我的孙子是一个集合,我会使用

Parent parent = _context.Parent.Include(p => p.Children.Select(c => c.Grandchild).FirstOrDefault();

【讨论】:

  • 如果 Children 为空怎么办? EF 是如何处理的?
猜你喜欢
  • 2011-08-23
  • 2019-01-03
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
相关资源
最近更新 更多