2

Model:

    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; }
    }

I have an existing Parent entity with a Children collection. After some operations i want to load newly added children objects to Parent's collection from database like this

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

But when i am doing this like that, the Grandchild object in every newly added collection element is null. I also tried to include grandchild in this way but still the Grandchild object is null.

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

How to correctly load the new items to the Parent's Children collection including Grandchild objects?

EDIT: I dont know why this question was marked as duplicate? My problem is: I already have existing (loaded/tracked) parent entity in one context instance (form) and then in another context instance (form) I modified entity child's collection ( add or remove child). Finally I want to load these newly added entries to parent entity collection in first context instance using one of this previously written methods but after that the newly added object are loaded but their grandchild's are nulls. I don't know how to correctly load these new child objects to existed (tracked) parent entity without getting a nulls.

Kuba.W
  • 35
  • 3

1 Answers1

1

I usually use the following(wihout load)

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

and if my Grandchild was a collection, I would use

Parent parent = _context.Parent.Include(p => p.Children.Select(c => c.Grandchild).FirstOrDefault();
Murilo
  • 1,112
  • 1
  • 18
  • 33