2

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!

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
kkdeveloper7
  • 497
  • 2
  • 11
  • 25
  • 1
    Cascaded delete deletes *children*, i.e. the records that contain the FK field. In this case, an Article is deleted cascading when a `MediaPlan` is deleted. You can't have it both ways. If you want it the other way around you must make `MediaPlan` refer to `Article` by FK. – Gert Arnold Jun 18 '19 at 21:42

1 Answers1

1

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.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114