New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Q: How to cascade deletes when DB-first FK is the wrong way around? #14658
Comments
@bert2 This is probably best handled by logic in an overridden public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
// Note that this is internal code to force cascade deletes to happen.
// It may stop working in any future release.
ChangeTracker.DetectChanges();
this.GetService<IStateManager>().GetEntriesToSave();
try
{
ChangeTracker.AutoDetectChangesEnabled = false;
foreach (var entry in ChangeTracker
.Entries<CritiqueText>()
.Where(e => Entry(e.Entity.Review).State == EntityState.Deleted))
{
entry.State = EntityState.Deleted;
}
}
finally
{
ChangeTracker.AutoDetectChangesEnabled = true;
}
return base.SaveChanges(acceptAllChangesOnSuccess);
} Some notes about this code:
|
Nice, this worked perfectly. Thanks for the quick answer! I refactored the solution to be based on attributes. Interested parties can find it in the test project repo. |
Unfortunately, it looks more like a hack rather than a robust solution. Moreover, if you have plans to allow configuring shapes of aggregates, you'll probably need to implement deletion of an aggregate as well irrespective of db's dependency direction. |
I'm currently working with a legacy DB where a one-to-one relation has been modeled the wrong way around; i.e. the foreign key column is stored on the entity which should be the principal entity of the relation. Consequently, EF is refusing to cascade-delete the should-be dependent entity of the relation.
TL;DR
Is there a way to specify the principal entity of a one-to-one relation independently of where the FK is stored?
Detailed explanation
Consider this model of a very similar schema:
Here a
Post
has a collection ofPositiveReviews
which each have aPraiseText
(yes, I know, it's a stupid example, but I hope it gets my point across). As you can see the FK of the relationPositiveReview
-PraiseText
is stored onPositiveReview
, effectively makingPraiseText
the principal entity of the relation. This means whenever aPositiveReview
gets deleted from aPost
, then the correspondingPraiseText
will not be deleted and remains orphaned in the DB.How can I convince EF to cascade-delete those
PraiseText
s?Steps to reproduce
I created a test project with integration tests that you can use to reproduce the issue:
The test DeletesTextWhenDeletingReview will fail.
Further details
EF Core version: 2.2.1
Database Provider: Microsoft.EntityFrameworkCore.Sqlite
Stackoverflow question: EF Core: How to cascade delete when DB-first FK is the wrong way around?
The text was updated successfully, but these errors were encountered: