简体   繁体   English

首先删除代码上的级联-一对零或一对

[英]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.

相关问题 EF6必需与可选的关系(一对零或一对)无法正常工作 - EF6 Required-to-Optional Relationship (One-to–Zero-or-One) not working correctly EF Core 中必需到可选关系(一对零或一)的最佳方法是什么? - What is the best method for Required-to-Optional Relationship (One-to–Zero-or-One) in EF Core? 仅具有一对零或一对关系在桌上设置组合键 - Set composite key on table with only One-to–Zero-or-One relations EF6配置必需的可选关系(一对一或一对一) - EF6 Configuring a Required-to-Optional Relationship (One-to–Zero-or-One 按代码映射零或一关系 - Mapping by code Zero-Or-One relationship 一个与HasForeignKey为零或一 - One to zero-or-one with HasForeignKey 首先通过数据注释在EF代码中实现一对一或零关系 - Implementing One to Zero-Or-One relationship in EF Code first by data annotation Entity Framework Core 零或一到零或一关系 - Entity Framework Core zero-or-one to zero-or-one relation 实体框架(EF)代码优先级联删除一对一或零关系 - Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship 带有级联删除的一对一映射的EF代码优先模型定义 - EF Code First Model definition for one to one mapping with cascade delete
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM