【发布时间】:2021-04-30 16:55:51
【问题描述】:
我正在尝试从数据库中删除User,User 有自己的Recipes。即使我在模型生成器中配置了级联删除,它也不起作用。
我得到的错误是:
SqlException:DELETE 语句与 REFERENCE 约束“FK_Recipes_AspNetUsers_ApplicationUserId”冲突。冲突发生在数据库“master”、表“dbo.Recipes”、列“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");
}
我一直在寻找解决方案一个小时,但没有任何效果。
配置 modulbuilder 似乎是几乎每个人的解决方案,但肯定对我不起作用。
【问题讨论】:
-
您是否一直配置级联删除行为?还是你最近添加的?如果您最近进行了更改,是否记得添加迁移并应用它?
标签: c# asp.net-mvc entity-framework entity-framework-core