How to cascade delete only on join table using Entity Framework Code First Fluent API

后端 未结 1 1618
误落风尘
误落风尘 2021-02-15 13:52

I\'m trying to map an existing database using Entity Framework Code First Fluent API. I\'m struggling on a situation with a many-to-many relationship and cascade delete.

1条回答
  •  有刺的猬
    2021-02-15 14:21

    But when I delete a Foo, I would like to delete the records on the join table but not on the child table. Meaning I want to delete records on Foo_Bar but not to extend this cascade to Bar.

    Is such a mapping possible?

    This is actually the only mapping that is possible. You cannot extend cascading delete to the Bar table because in the relationship (from database schema perspective) the Foo_Bar join table is the dependent in the relationship and Bar is the principal. Generally cacscading delete is only in effect if you delete the principal but not when you delete the dependent.

    So, you don't need to worry that a Bar could be deleted when you delete a Foo and you don't have to apply any special setting for this.

    But you have a problem when you have removed the ManyToManyCascadeDeleteConvention. It acts globally for the whole model and there is no option to turn on cascading delete again for a specific many-to-many relationship. (There is no WillCascadeOnDelete(true) for many-to-many relationship like there is one for one-to-many or one-to-one relationships.)

    Are you sure that removing the ManyToManyCascadeDeleteConvention is really required in your model? I never encountered a model where it would make sense to not delete the related entries in the join table when one of the joined entities (Foo or Bar) is deleted.

    0 讨论(0)
提交回复
热议问题