我在 Entity Framework Core 中遇到了 DELETE CASCADE 问题,我似乎找不到好的解决方案。
这是我的模型的超级简化版本:
User {UserID, Name}
Recipe {RecipeID, UserID}
Ingredient {IngredientID, UserID}
RecipeIngredient {RecipeID, IngredientID} *RecipeIngredient is the many-to-many table.
Recipe 和 Ingredient 的 UserID 都标记为 [Required],RecipeIngredient 的 RecipeID 和 IngredientID 标记为 [Required]。
问题是 SQL 不会创建数据库,因为有多个到 RecipeIngredient 的级联删除路径(“引入 FOREIGN KEY 约束...可能会导致循环或多个级联路径”)。
所以我陷入了困境......我已经想出了一些想法,但没有任何效果。
这里有设计解决方案吗?我想保留我的外键,因为强制执行它是有意义的,但如果有设计解决方案,我对此持开放态度。
我的下一个想法是删除所有指向用户的 FK - 我必须通过 C# 代码在 DELETE 期间强制执行引用完整性,并且我可以使用 [Required] 在 CREATE 期间强制输入数据。问题是 - [必需] 创建一个 FK,并添加“ON DELETE CASCADE”,这使我们又回到了多重级联删除路径问题。我真的很想保留[必需],因为与 Razor 页面、客户端验证和错误等的巧妙集成。
-
下一个想法,在 OnModelCreating(...) 中将级联行为设置为 SetNull:
modelBuilder.Entity()。
HasOne(i => i.User)
.WithMany(u => u.Ingredients)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity()
.HasOne(r => r.Source)
.WithMany(s => s.Recipes)
.OnDelete(DeleteBehavior.SetNull);
但这会引发异常,因为即使我在 Ingredient 和 Recipe 中的属性设置为 Nullable:
[Required(ErrorMessage = "User ID is required.")]
public Nullable<int> UserID { get; set; }
...由于 [Required] 属性,EF 仍将其创建为 NOT NULL 数据库列。
对此有什么解决办法呢?据我所知,我应该删除 User 的所有 FK,并尝试将其强制作为 CREATE 上的必填字段,但我没有找到使用数据注释来做到这一点的方法,而我想这样做将这个逻辑保留在我的代码优先模型中。