[英]Delete Cascade on Code First - One-to–Zero-or-One
I have an Entity named Items , then I have several entities that have a foreign key (NOT NULLABLE) to this table key ItemId . 我有一个名为Items的实体,然后有几个具有此表键ItemId的外键(NOT NULLABLE)的实体。
Then I have another table named Soldiers that depends also on Items , but in this case it's a (NULLABLE) foreign key. 然后,我还有一个名为Soldiers的表,它也依赖于Items ,但是在这种情况下,它是一个(NULLABLE)外键。
When I delete an item on the Items table I get an error regarding items that exist on the Soldiers table. 当我删除“ 项目”表上的项目时,我收到有关“ 士兵”表上存在的项目的错误。 If I don't have Soldiers with items I don't get the error, and all the other tables are correctly cascade deleted. 如果我没有带物品的士兵 ,我不会收到错误消息,并且所有其他表都已正确级联删除。
I guess I have to put something on the Fluent API to cascade delete also on this table, but I am not sure how to do it. 我想我必须在Fluent API上放一些东西,以便在此表上也级联删除,但是我不确定该怎么做。
Thanks 谢谢
You can configure it with WithCascadeOnDelete
. 您可以使用WithCascadeOnDelete
对其进行配置。
modelBuilder.Entity<Item>()
.HasMany(i => i.Soldiers)
.WithOptional(s => s.Item)
.HasForeignKey(s => s.ItemId)
.WillCascadeOnDelete(true);
Or 要么
modelBuilder.Entity<Soldier>()
.HasOptional(s => s.Item)
.WithMany() // -> use i => i.Soldiers if any
.HasForeignKey(i => i.ItemId)
.WillCascadeOnDelete(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.