locked
How to insert a Parent along with it's children in EF Core RRS feed

  • Question

  • User-1659924024 posted

    In my ASP.NET Core 1.1.1 MVC web app, the Intellisense of the code editor of VS2017 does not recognize .child at line p.child.Add(c1);. What is the correct way of adding a Parent along with it's children.

    ...
    Parent p = new Parent { Name = "some name" , FY = SelectedYear, ... };
    
    Child c1 = new Child { ItemName = "Abc"};
    Child c2 = new Child { ItemName = "Rst"};
    
    p.child.Add(c1);
    p..child.Add(c2);
    
    _context.Add(p);
    _context.SaveChanges();
    

    Monday, October 2, 2017 3:45 AM

All replies

  • User1120430333 posted

    A parent object is going to have children collection.

     Parent p = new Parent { Name = "some name" , FY = SelectedYear, ... };
    p.children= new List<child>();

    p.children.Add(c1);
    p..children.Add(c2);

    context.Add(p);
    _context.SaveChanges();

    This is assuming that you setup the parent objet to have a children collection within parent.

    Parent { Name = "some name" , FY = SelectedYear, ... };


    Monday, October 2, 2017 10:22 AM
  • User-1659924024 posted

    Visual studio editor does not recognize p.children at the line p.children= new List<child>();

    Monday, October 2, 2017 6:09 PM
  • User-707554951 posted

    Hi  namwam,

    From your description, you want to add entity with its related entities (navigated properties) using entity framework.

    If that the case, you should use different code based on your relationship between parent entity and child class.

    For your case, you should have entity as below:

     public class Parent
        {
            [Key]
            public string Name { get; set; }
            public string FY { get; set; }
            [ForeignKey("ChildRefId")]       
            public virtual ICollection<Child> childs { get; set; }
        }
        public class Child
        {
            [Key]
            public string ItemName { get; set; }
            public Parent Parent { get; set; }
        }
     public class ParentChildcontext:DbContext
        {
            public DbSet<Parent> Parents { get; set; }
            public DbSet<Child> Childs { get; set; }
        }

    Then you could use the following code:

     ParentChildcontext _context = new ParentChildcontext();
                Child c1 = new Child { ItemName = "Abc" };
                Child c2 = new Child { ItemName = "Rst" };
                Parent p = new Parent { Name = "some name", FY = "SelectedYear", };
                p.childs.Add(c1);
                p.childs.Add(c2);
                _context.Parents.Add(p);
                _context.SaveChanges();

    Please refer to the tutorial in the link below:

    http://www.entityframeworktutorial.net/EntityFramework4.3/add-one-to-many-entity-using-dbcontext.aspx

    Best regards

    Cathy

    Tuesday, October 3, 2017 2:53 AM