TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
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
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"
);
}
Reply
Answers (
4
)
Authenticate User
encoding and decoding