I have a class called Section
public class Section { public Section() { construct(0); } public Section(int order) { construct(order); } private void construct(int order) { Children = new List<Section>(); Fields = new List<XfaField>(); Hint = new Hint(); Order = order; } [Key] public int Id { get; set; } public int FormId { get; set; } public string Name { get; set; } [InverseProperty("Parent")] public List<Section> Children { get; set; } public List<XfaField> Fields { get; set; } public Section Parent { get; set; } public Hint Hint { get; set; } public int Order { get; private set; } #region Methods public void AddNewChild() { AddChild(new Section { Name = "New Child Section", FormId = FormId, }); } private void AddChild(Section child) { child.Parent = this; if (Children == null) Children = new List<Section>(); int maxOrder = -1; if(Children.Count() > 0) maxOrder = Children.Max(x => x.Order); child.Order = ++maxOrder; Children.Add(child); FactoryTools.Factory.PdfSections.Add(child); } // Other methods here #endregion } I am trying to add a new child Section to an already existing parent like this:
private void AddChildSection() { var parent = FactoryTools.Factory.PdfSections.FirstOrDefault(x => x.Id == ParentId); if (parent == null) throw new Exception("Unable to create child because parent with Id " + ParentId.ToString() + " doesn't exist."); parent.AddNewChild(); FactoryTools.Factory.SaveChanges(); } When I look at the database, I see that a new row has been added, so for example:
Id Name Parent_Id Hint_Id FormId Order 19 New Child Section 1 27 1 0 However, when I load the parent Section, the Children property is always of Count 0, like this:
public ActionResult EditSection(int formId, int sectionId) { var model = FactoryTools.Factory.PdfSections.FirstOrDefault(x => x.Id == sectionId); if (model == null || model.FormId != formId) model = new Section(); //model.Children = FactoryTools.Factory.PdfSections.Where(x => x.Parent.Id == sectionId).ToList(); return PartialView(model); } Of course, when I manually add the children, then they are there (in the above code, by uncommenting the model.Children = ... line)
I am used to the NHibernate way of doing things and am therefore quite frustrated that the above, seemingly simple, task is not working in EntityFramework, what am I doing wrong?