gpt4 book ai didi

c# - 如何在自引用关系上设置级联?

转载 作者:太空狗 更新时间:2023-10-29 21:45:02 26 4
gpt4 key购买 nike

我有一个默认场景,您有 Category 本身、RootCategoryChildCategories。如何指定我的流畅模型构建器在删除时级联所有子类别?

型号

public class Category
{
public int Id { get; set; }
public string Name { get; set; }

public virtual Category RootCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
public virtual ICollection<Item> Items { get; set; }
}

我尝试过的

我曾尝试使用流畅的模型构建器,但是当我尝试更新数据库时,这个会出错。

Introducing FOREIGN KEY constraint 'FK_dbo.Categories_dbo.Categories_RootCategory_Id' on table 'Categories' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>().HasOptional(x => x.RootCategory).WithMany(x => x.ChildCategories).WillCascadeOnDelete(true);
}

最佳答案

我遇到了同样的问题。关于fluent API configuraion,我不知道你能不能在那里做。您可以做的是将 WillCascadeOnDelete 设置为 false,然后自己删除 ChildCategories。

private void DeleteChildCategories(Category category) 
{
foreach (Category subCategory in category.ChildCategories.ToList())
{
if (subCategory.SubCategories.Count() > 0)
{
DeleteChildCategories(subCategory);
}
else
{
_db.Category.Remove(subCategory);
}
}
_db.Category.Remove(category);
}

然后,您可以在 Controller 操作中删除类别时调用 DeleteChildCategories。

DeleteChildCategories(Category);
_db.SaveChanges();

希望这对您有所帮助。

标记

关于c# - 如何在自引用关系上设置级联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18702071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com