Marius Vasile

Marius Vasile

  • 595
  • 1.9k
  • 146.4k

asp.net core EF cascade delete error

May 24 2021 10:20 AM
I have a succesion of 2 related tables, see below
  1. public class HazardsLocation    
  2. {    
  3.     [Key]    
  4.     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]    
  5.     public string IdHL { getset; }    
  6.     [Required]    
  7.     public string HazLocation { getset; }    
  8.     public string OrgID { getset; }    
  9.     public ICollection<HazardsCategory> HazardsCategories { getset; }    
  10. }    
  11.   
  12. public class HazardsCategory    
  13. {    
  14.     [Key]    
  15.     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]    
  16.     public string IdHCA { getset; }    
  17.     [Required]    
  18.     public string HazCategory { getset; }    
  19.     public string IdHL { getset; }    
  20.     [ForeignKey("IdHL")]    
  21.     public HazardsLocation HazardsLocation { getset; }    
  22. }  
and relation in Context
  1. modelBuilder.Entity<HazardsLocation>()    
  2.                 .HasMany(a => a.HazardsCategories)    
  3.                 .WithOne(a => a.HazardsLocation)    
  4.                 .OnDelete(DeleteBehavior.Cascade);    
  5.     
  6.             modelBuilder.Entity<HazardsCategory>()    
  7.                 .HasMany(a => a.HazardsSources)    
  8.                 .WithOne(a => a.HazardsCategory)    
  9.                 .OnDelete(DeleteBehavior.Cascade);   
but when I try to delete one item from the first table I get the following error
 
SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_HazardsCategories_HazardsLocations_IdHL". The conflict occurred in database "aspnet-RoSafety-53bc9b9d-9d6a-45d4-8429-2a2761773502", table "dbo.HazardsCategories", column 'IdHL'.
 
The delete procedure
  1. public async Task<IActionResult> OnPostDeleteAsync(string idhl)    
  2. {    
  3.     if (idhl == null)    
  4.     {    
  5.         return NotFound();    
  6.     }    
  7.     var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);    
  8.     var orgid = await _context.UsersData.Where(s => s.Id == userId).Select(s => s.OrgID).FirstOrDefaultAsync();    
  9.   
  10.     var hazard = await _context.HazardsLocations.FindAsync(idhl);    
  11.     _context.HazardsLocations.Remove(hazard);    
  12.     _context.SaveChanges();    
  13.   
  14.     return RedirectToPage("/HazId/HazLocation");    
  15. }  

Answers (4)