问题描述
我有被安排进了分级中的类,像这样的:
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.
我没意识到在第一,但我删除容器TestContainer犯规删除的项目。
I didnt realize at first but deleting my container TestContainer doesnt delete the items.
行,没问题吧?
我插入如下功能(这可能是非常难看,但我仍然在这里原型阶段)
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
,同时节省不为他们的关系公开外键属性的实体时出现错误。该EntityEntries属性将返回null,因为一个单一的实体不能被认定为异常的根源。
"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 exception."
我最好的级联如何删除项目及其所有儿童,使我没有在数据库中的孤儿? (像现在这样)
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)
推荐答案
而不是删除上的外键的实体,并使用EF的死者您可以启用级联删除
的你的数据库。它比产生多个删除语句更高效
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.
修改
您需要添加 WillCascadeOnDelete()
在配置模型
modelBuilder.Entity<Item>().HasMany(i => i.Children)
.WithOptional(i => i.Parent)
.HasForeignKey(i => i.ParentId)
.WillCascadeOnDelete();
这篇关于EF4 code第一 - 从数据库中删除父删除时,所有的孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!