locked
Unable to execute Cascade delete feature of in Entity Framework Core 3.1 RRS feed

  • Question

  • User-2054057000 posted

    I am trying to perform Cascade delete but it is not working.

    My entities and DB Context are:

    public class City
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public int FKCountry { get; set; }
    
        public Country Country { get; set; }
    }
    
    public class Country
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public ICollection<City> City { get; set; }
    }
    
    public class CompanyContext : DbContext
    {
        public DbSet<City> City { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
            }
        }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //Write Fluent API configurations here
    
            modelBuilder.Entity<City>()
                        .HasOne(e => e.Country)
                        .WithMany(e => e.City)
                        .OnDelete(DeleteBehavior.Cascade)
                        .HasForeignKey(e => e.FKCountry);
        }
    }

    Note that I have applied cascade delete with the code:

    .OnDelete(DeleteBehavior.Cascade)

    With my code in the controller I am deleting cities with id 1.

    using (var context = new CompanyContext())
    {
        City city = context.City.Where(a => a.Id == 1).Include(x => x.Country).FirstOrDefault();
        context.Remove(city);
        await context.SaveChangesAsync();
    }
    

    The cities get deleted but the respective country record (which should be deleted according to cascade deleted) does not get deleted. WHY?

    Wednesday, August 12, 2020 5:59 PM

Answers

  • User475983607 posted

    Cascade deletes occur when the primary key is deleted.  The associated foreign keys are also deleted.  You're deleting the foreign key, city, not the primary; country.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 12, 2020 6:12 PM