EF4 Code first - delete all children when deleting parent from db?
I have a class that gets arranged into a hierarchy, such as this:
class TestContainer
{
... bla bla bla...
public Virtual Item Items {get;set;}
}
Class Item
{
[Key]
public int ID {get;set;}
public string PropA {get;set;}
public string PropB {get;set;}
[InverseProperty("Parent")]
public virtual ICollection<Item> Children { get; set; }
[InverseProperty("Contents")]
public virtual Item Parent { get; set; }
}
So, I have an update method that lets a user upload an updated set of children.
I didnt realize at first but deleting my container TestContainer doesnt delete the items.
Ok, No problem right?
I inserted the following functions (which is probably very ugly but I am still in the prototyping phase here)
private void DeleteItems(TestContainer existingContainer)
{
//setup a flat list for deletion
List<Item> trashCan = new List<Item>();
//delete the old CI's from the database
BuildDeletionList(existingContainer.Items, ref trashCan);
foreach (Item item in trashCan)
{
context.Items.Remove(item);
}
}
private void BuildDeletionList(ICollection<Item> items, ref List<Item> trashCan)
{
if (items != null)
{
foreach (Item item in items)
{
BuildDeletionList(item, ref trashCan);
}
}
}
private void BuildDeletionList(Item item, ref List<Item> trashCan)
{
if (Item.Children != null)
{
foreach (Item child in Item.Children)
{
BuildDeletionList(item, ref trashCan);
}
}
item.Children.clear();
trashCan.Add(item);
}
The problem here is that this either crashes my test server, or when I remove the recursive bit (and only remove parents -- testing out what is going wrong at this point), I get the following error
"An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exce开发者_高级运维ption."
How can I best cascade delete an Item and all of its Children, so that I do not have orphans in the database? (As I do now)
Instead of deleting an entity and its decedents using EF you can enable Cascade delete
on the foreign key on your database. It is much more efficient than generating multiple delete statements.
Edit
You need to add WillCascadeOnDelete()
when you configure the model
modelBuilder.Entity<Item>().HasMany(i => i.Children)
.WithOptional(i => i.Parent)
.HasForeignKey(i => i.ParentId)
.WillCascadeOnDelete();
精彩评论