I have a succesion of 2 related tables, see below
- public class HazardsLocation
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public string IdHL { get; set; }
- [Required]
- public string HazLocation { get; set; }
- public string OrgID { get; set; }
- public ICollection<HazardsCategory> HazardsCategories { get; set; }
- }
-
- public class HazardsCategory
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public string IdHCA { get; set; }
- [Required]
- public string HazCategory { get; set; }
- public string IdHL { get; set; }
- [ForeignKey("IdHL")]
- public HazardsLocation HazardsLocation { get; set; }
- }
and relation in Context
- modelBuilder.Entity<HazardsLocation>()
- .HasMany(a => a.HazardsCategories)
- .WithOne(a => a.HazardsLocation)
- .OnDelete(DeleteBehavior.Cascade);
-
- modelBuilder.Entity<HazardsCategory>()
- .HasMany(a => a.HazardsSources)
- .WithOne(a => a.HazardsCategory)
- .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
- public async Task<IActionResult> OnPostDeleteAsync(string idhl)
- {
- if (idhl == null)
- {
- return NotFound();
- }
- var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
- var orgid = await _context.UsersData.Where(s => s.Id == userId).Select(s => s.OrgID).FirstOrDefaultAsync();
-
- var hazard = await _context.HazardsLocations.FindAsync(idhl);
- _context.HazardsLocations.Remove(hazard);
- _context.SaveChanges();
-
- return RedirectToPage("/HazId/HazLocation");
- }