I have an object with a self referencing parent child relationship:
[Table("Content")]
public class Content
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ContentID { get; set; }
public string Text { get; set; }
public int? ParentID { get; set; }
public virtual Content Parent { get; set; }
private ICollection<Content> _contents { get; set; }
public virtual ICollection<Content> Contents
{
get { return _contents ?? (_contents = new HashSet<Content>()); }
set { _contents = value; }
}
}
I am trying to work with the edit function so that if the parent ID changes, the object is correctly removed from the OLD parent's children and added to the new one (or is correctly set to null)
I have tried a number of combinations in order to make the code correctly change the parent ID but I am just not able to crack the correct thing to do here.
[HttpPost]
public ActionResult Edit(Content content)
{
if (ModelState.IsValid)
{
Content oldContent = context.Contents
.Where<Content>(c => c.ContentID == content.ContentID)
.Single<Content>();
// If the parent has changed.
if (content.ParentID != oldContent.ParentID)
{
// if the old parent is not NULL remove from collection
if (oldContent.ParentID != null) {
Content oldParent = context.Contents
.Where<Content>(c => c.ContentID == oldContent.ParentID)
.Single<Content>();
oldParent.Contents.Remove(content);
context.Entry(oldParent).State = EntityState.Modified;
context.SaveChanges();
}
// if the new parent is not NULL add to the new collection
if (content.ParentID != null) {
Content parent = context.Contents
.Where<Content>(c => c.ContentID == content.ParentID)
.Single<Content>();
parent.Contents.Add(content);
context.Entry(parent).State = EntityState.Modified;
context.SaveChanges();
}
}
context.Entry(oldContent).CurrentValues.SetValues(content);
context.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PossibleParents = context.Contents;
return View(content);
}
The problem is that the data table has two fields related to ParentID - the first ParentID
is correctly changing, the second, Parent_ContentID
is not. The second one is used for looping through the .Contents
property from the parent.
What am I missing? How can I remove the current object from the "related objects" collection of the parent?