单个 table 上的 EF 级联删除

EF cascade delete on single table

我有一个Categoryclass

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);

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

SQL 服务器不允许您在自引用关系上设置级联删除,可能会出现循环逻辑问题。这样您就可以删除一个类别及其子类别:

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();