如何删除没有子类别的类别

How to remove category without sub category

如何删除没有子类别的类别?

类别模型:

   public class Category 
    {
        public virtual int Id{ get; set; }
        public virtual string Name { get; set; }
        public virtual Category Parent { get; set; }
        public virtual int? ParentId { get; set; }
    }

数据:

Id          ParentId    Name
1           null        Hot
2           1           Soup
3           1           Coffee
4           3           Decaf Coffee
5           null        Cold
6           5           Iced Tea

我需要使用 Id=1 删除类别,但出现以下错误:

The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.Categories_dbo.Categories_ParentId". The conflict occurred in database "ProjectDatabase", table "dbo.Categories", column 'ParentId'. The statement has been terminated.

我的删除代码:

  public void Delete(int categoryId)
        {
            var category = _categories.First(d => d.Id == categoryId);
            _categories.Remove(category);
        }

类别配置:

 public class CategoryConfig : EntityTypeConfiguration<Category>
    {
        public CategoryConfig()
        {
            ToTable("Categories");
            HasOptional(x => x.Parent)
            .WithMany()
            .HasForeignKey(x => x.ParentId)
            .WillCascadeOnDelete(false);

       }
    }

您无法删除带有 Id=1 的类别,因为有子类别引用它(SoupCoffee) .在您的删除方法中,您必须先将这些项目的 ParentId 更改为另一个现有元素(或 null),或者在使用 [= 删除类别之前删除这些项目10=].

嗯,根据 documentation如果依赖实体上的外键是 nullable,Code First 不会在关系上设置级联删除(你是明确地做),当主体被删除时,外键将设置为 null.

我不知道为什么在你的情况下不这样做,可能是因为你正在处理单向关系并且你的父类别中没有子集合,所以 EF 无法设置FK 属性到子类别中的 null,但您可以尝试以下操作:

var category = _categories.First(d => d.Id == categoryId);
var children=_categories.Where(d=>d.ParentId==categoryId);
foreach(var c in children)
   c.ParentId=null;
_categories.Remove(category);