单个表上的EF级联删除

时间:2015-08-08 07:06:01

标签: c# entity-framework-6 cascade

我有Category

public class Category : BaseEntity {
    //[Key]
    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    //public int Id { get; private set; }
    public string Name { get; set; }
    public int Owner { get; set; }
    public int? PId { get; private set; }
    [ForeignKey("PId")]
    public Category Parent { get; set; }
    public ICollection<Category> Subcategories { get; set; }
}

一个类别可能有一个Parent类别,可选,并且有很多子类别,就像树一样。

删除类别时,我想删除级联中的子类别。我试过下面的代码:

 public CategoryMapping() {
        HasKey(t => t.Oid);
        Property(t => t.Oid).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(t => t.CreatedDate).IsRequired();
        Property(t => t.Uid).IsRequired().HasMaxLength(50);
        Property(t => t.Name).IsRequired();

        ToTable("W_CATEGORY");

        this.HasMany(wi => wi.Subcategories).WithOptional(wi => wi.Parent).WillCascadeOnDelete(true);

它无法正常工作。谁能帮我?感谢。

1 个答案:

答案 0 :(得分:1)

SQL Server不允许您在自引用关系上设置级联删除,可能存在周期性逻辑问题。这样您就可以删除包含其子项的类别:

public void Remove(int id)
{
    var selectedCategory = _category.Find(id);
    _category.Where(x => x.ParentId == id).Load();
    _category.Remove(selectedCategory);
}

或者您可以这样使用:

private Stack<Category> GetChildsAndRoot(Category category)
{
            var stack = new Stack<Category>();
            var queue = new Queue<Category>();
            stack.Push(category);
            queue.Enqueue(category);
            while (queue.Any())
            {
                var currCategory = queue.Dequeue();
                foreach (var child in currCategory.Childs)
                {
                    queue.Enqueue(child);
                    stack.Push(child);
                }
            }

            return stack;
}
var category = _categoryRepository.GetByID(id);

var nodes = GetChildsAndRoot(category);
while (nodes.Any())
{
        _categoryRepository.Delete(nodes.Pop());
}

_unitOfWork.SaveChanges();