0

My understanding is that, using Fluent API, this code:

modelBuilder.Entity<Parent>()
    .HasOptional(p => p.Child)
    .WithOptionalPrincipal(c => c.Parent)
    .Map(m => m.MapKey("ParentId"))
    .WillCascadeOnDelete(true);

..should cause Child to be deleted whenever the linked Parent is deleted. However, I can't get this to work.

Whenever I delete a Parent, the ParentId field of the corresponding Child is simply set to null instead of deleting the child.

I checked this question, but the answer there is confusing to me because it seems to make the parent the Dependent side, and it didn't actually work for me anyway.

What am I doing wrong?

  • 1
    Look at the unaccepted answer of that question. The principal should be required. – Gert Arnold Dec 09 '17 at 10:25
  • @GertArnold If one of the sides is required, it's a '1-to-0..1' which doesn't work for my case. I need both sides to be optional. Edit: in order for it to make sense, let me explain: 1) Any `Parent` might or might not have a `Child`. 2) Any `Child` might have a `Parent` or another parent (e.g., `ParentB`). That's why I need both sides to be optional. – 41686d6564 stands w. Palestine Dec 09 '17 at 10:27
  • Then there is nothing you can do. EF6 treats cascade delete on optional FK relationships differently - basically something like *cascade update set to null*. EF Core provides more cascading options (than EF6 simple `true` / `false` which apparently is insufficient). – Ivan Stoev Dec 09 '17 at 10:33
  • @IvanStoev Hmm, it looks that way. I think I'll have to delete the child manually when deleting its parent. But is there a reason for that behavior? And is it documented somewhere? – 41686d6564 stands w. Palestine Dec 09 '17 at 10:48
  • 1
    Good question. Actually it's mentioned in [Enabling Cascade Delete](https://msdn.microsoft.com/en-us/library/jj591620(v=vs.113).aspx#Anchor_5): *If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.* – Ivan Stoev Dec 09 '17 at 11:18

0 Answers0