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?
Helping you always. Don't forget to click "Mark as Answer" on the post that helped you.
♠ ASP.NET Core Tutorials → Start from the Beginning and become an Expert in 30 days time ♠
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.
Participant
1253 Points
943 Posts
Unable to execute Cascade delete feature of in Entity Framework Core 3.1
Aug 12, 2020 05:59 PM|yogyogi|LINK
I am trying to perform Cascade delete but it is not working.
My entities and DB Context are:
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.
The cities get deleted but the respective country record (which should be deleted according to cascade deleted) does not get deleted. WHY?
♠ ASP.NET Core Tutorials → Start from the Beginning and become an Expert in 30 days time ♠
All-Star
53721 Points
24048 Posts
Re: Unable to execute Cascade delete feature of in Entity Framework Core 3.1
Aug 12, 2020 06:12 PM|mgebhard|LINK
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.