0

I have an Entity named Items, then I have several entities that have a foreign key (NOT NULLABLE) to this table key ItemId.

Then I have another table named Soldiers that depends also on Items, but in this case it's a (NULLABLE) foreign key.

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.

Thanks

Heavy JS
  • 51
  • 7

1 Answers1

1

You can configure it with 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);
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67
  • Thanks for your answer, but I cannot see the Soldiers property on the ``i => i.``. – Christopher Bailey Aug 18 '14 at 18:50
  • @ChristopherBailey, you can add `public virtual ICollection Soldiers {get;set;}` on `Item`, I also provide another option to configure it from `Soldier` – Yuliam Chandra Aug 18 '14 at 18:52
  • It does not work :( I get the following when I run the ``update-database`` ``Introducing FOREIGN KEY constraint 'FK_dbo.Soldiers_dbo.Items_ItemId' on table 'Soldiers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint.`` – Christopher Bailey Aug 18 '14 at 20:58
  • @ChristopherBailey, could you post your classes and configuration ? – Yuliam Chandra Aug 19 '14 at 03:09
  • I found that I had another cascade path that might be delete the same table data. It's now ok. Thanks for your help. +1 – Christopher Bailey Aug 19 '14 at 10:25