如何删除没有子类别的类别?
类别模型:
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);
}
}
最佳答案
嗯,根据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);
关于c# - 如何删除没有子类别的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36311663/