I'm trying to delete User
from database, User
has its own Recipes
. Cascade delete doesn't work even though I configured it in model builder.
The error I'm getting is:
SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_Recipes_AspNetUsers_ApplicationUserId". The conflict occurred in database "master", table "dbo.Recipes", column 'ApplicationUserId'.
AplicationUser.cs :
namespace WebApplication.Models
{
public class ApplicationUser : IdentityUser
{
public ICollection<Recipe> Recipes { get; set; }
}
}
Recipe.cs
namespace WebApplication.Models
{
public class Recipe
{
[Key]
public Guid Id { get; set; }
[Required]
public string RecipeName { get; set; }
[Required]
public string RecipeContent { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
}
ApplicationDbContext.cs
namespace WebApplication.Models
{
public class ApplicationDbContext : IdentityDbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().HasMany(e => e.Recipes).WithOne(e => e.ApplicationUser)
.OnDelete(DeleteBehavior.ClientCascade);
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Recipe> Recipes { get; set; }
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
}
}
UserController.cs
public IActionResult Delete(string id)
{
var user = _applicationDbContext.Users
.Where(u => u.Id == id).FirstOrDefault();
return View(user);
}
[HttpPost]
public IActionResult Delete(ApplicationUser appuser)
{
var user = _applicationDbContext.Users
.Where(u => u.Id == appuser.Id).FirstOrDefault();
_applicationDbContext.Users.Remove(user);
_applicationDbContext.SaveChanges();
return RedirectToAction("Index");
}
I've been looking for solution to that for like an hour and nothing works.
Configuring modulbuilder seems to be solution for almost everyone but certainly doesn't work for me.
question from:
https://stackoverflow.com/questions/65909283/cascade-delete-doesnt-work-in-asp-net-5-and-ef-core 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…