I have a one to one relationship set up on ef core. When i try to delete Article
entity I need to cascade MediPlan
since it is one to one
relationship. When I Delete Article
, MediaPlan
is not getting removed.
Here is set up.
public class Article
{
public int Id { get; set; }
public int MediaPlanId { get; set; }
public MediaPlan MediaPlan { get; set; }
}
and
public class MediaPlan
{
public int Id { get; set; }
public Article Article { get; set; }
}
Context
modelBuilder.Entity<Article>().HasOne(x => x.MediaPlan).WithOne(x => x.Article);
Code to delete
var article = await _db.Articles
.Include(x=>x.MediaPlan)
.SingleAsync(x=>x.Id == id);
_db.Articles.Remove(article);
await _db.SaveChangesAsync();
Do I have to set a FK on MediaPlan
entity as well?
Thank you!
I see your One-to-One
Fluent API configuration is not written in correct way as you did not specify the dependent entity. Your Fluent API configuration should be written as follows:
modelBuilder.Entity<Article>().HasOne(a => a.MediaPlan)
.WithOne(mp => mp.Article)
.HasForeignKey<Article>(a => a.MediaPlanId)
.OnDelete(DeleteBehavior.Cascade);
Now deleting a MediaPlan
will also delete its dependent Article
as follows:
var mediaPlanToBeDeleted = await _db.MediaPlans.FirstOrDefaultAsync(x=>x.Id == id);
_db.MediaPlans.Remove(mediaPlanToBeDeleted);
await _db.SaveChangesAsync();
Now if you want the reverse behavior then you have to reverse your Fluent API configuration.
Note: Only deleting the principal entity will cascade delete the dependent entity. Vice-versa is not possible.