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