How to remove child items correctly
Posted: Tue 13 Dec 2011 14:44
I have a foollowing scenario: there is entity A and entity B, that is "child" of A (one-to-many relationship). User selects an instance of A with the given id from DB, makes a copy of it and copies of all connected B instances. After that some children of type B are marked as removed, and DeleteAllOnSubmit() is called to notify data context.
After SubmitChanges() all entities, even the "deleted" ones appear to be in the DB. Following code would throw an exception "Cannot remove an entity that has not been attached":
If I don't make a copy of a1 instance and just modify it the same way, everything works as expected. Note, that I never call InsertOnSubmit() for newly created instances. I imagine, that all the "magic" is done through
But if I call InsertOnSubmit() for newly created A and B instances, nothing changes.
So how could I achieve the desired functionality? Or am I doing something wrong?
I use LinqConnect with DotConnect for Oracle 6.60 Professional (Trial version).
Code: Select all
var context = new MyDataContext();
var a1 = context.A.First(item => item.Id == 1);
var a2 = new A();
a2.Name = a1.Name;
a2.A1 = a1;
a2.ParentId = a1.Id;
foreach (var b1 in a1.Bs)
{
var b2 = new B();
b2.Value = b1.Value;
b2.A = a2;
a2.Bs.Add(b2);
}
/* Here user decides to delete some of a2's children of type B, and all removed items are placed into var IList deletedItems */
context.B.DeleteAllOnSubmit(deletedItems);
context.SubmitChanges();
Code: Select all
foreach (var b in deletedItems)
{
a2.Remove(b);
}
Code: Select all
a2.A1 = a1;
So how could I achieve the desired functionality? Or am I doing something wrong?
I use LinqConnect with DotConnect for Oracle 6.60 Professional (Trial version).