【问题标题】:Cascade delete Entity Framework Identity User with relations级联删除具有关系的实体框架身份用户
【发布时间】:2020-09-26 14:04:10
【问题描述】:

我使用 .net Core 3.1 脚手架 Identity 并用我自己的类对其进行了扩展。但是当我在 DeletePersonalData.OnPostAsync() 中使用构建时,由于我与其他类的关系而失败。我不明白我是如何删除所有扩展类的。

错误信息:

SqlException:DELETE 语句与 REFERENCE 冲突 约束“FK_Workspaces_AspNetUsers_OwnerId”。发生了冲突 在数据库“myupload”、表“dbo.Workspaces”、“OwnerId”列中。这 声明已终止。 Microsoft.Data.SqlClient.SqlCommand+c.b__164_0(任务 结果)

扩展身份:

    public class ApplicationDbContext : IdentityDbContext<IdentityUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }

        public DbSet<MyFile> MyFiles { get; set; }
        public DbSet<Workspace> Workspaces { get; set; }
        public DbSet<WorkspacePermission> WorkspacePermissions { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
            builder.Entity<Workspace>()
                .HasOne(p => p.Owner)
                .WithMany()
.OnDelete(DeleteBehavior.Cascade);

            builder.Entity<MyFile>()
                .HasOne(p => p.Workspace)
                .WithMany(b => b.MyFile);
        }
    }

以及删除方法:

        public async Task<IActionResult> OnPostAsync()
    {
        var user = await _userManager.GetUserAsync(User);
        if (user == null)
        {
            return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
        }

        RequirePassword = await _userManager.HasPasswordAsync(user);
        if (RequirePassword)
        {
            if (!await _userManager.CheckPasswordAsync(user, Input.Password))
            {
                ModelState.AddModelError(string.Empty, "Incorrect password.");
                return Page();
            }
        }

        var result = await _userManager.DeleteAsync(user);
        var userId = await _userManager.GetUserIdAsync(user);
        if (!result.Succeeded)
        {
            throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
        }

        await _signInManager.SignOutAsync();

        _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

        return Redirect("~/");
    }
}

其中一类:

public class Workspace
{
    // Base
    public Guid WorkspaceID { get; set; }
    public string Name { get; set; }

    // Security
    public virtual IdentityUser Owner { get; set; }
    public string Password { get; set; }

    // Files
    public virtual ICollection<MyFile> MyFile { get; set; }


    // Statistics

    public Workspace()
    {
    }
}

【问题讨论】:

  • @GertArnold 那么我如何用级联删除来定义它们?我首先使用实体​​框架和代码。
  • @GertArnold 我没有成功。我添加了我认为没有成功的方法。相同的错误信息
  • @GertArnold 感谢您的指点。我终于解决了。如果您希望我接受您的回答,请添加一个。

标签: razor .net-core entity-framework-6 asp.net-core-mvc


【解决方案1】:

使用 Fluent API,我设法在 OnModelCreating 方法中使用此代码将 Cascade Delete 添加到 IdentityUser。

         builder.Entity<Workspace>()
                .HasOne(p => p.Owner)
                .WithMany()
.OnDelete(DeleteBehavior.Cascade);

            builder.Entity<MyFile>()
                .HasOne(p => p.Workspace)
                .WithMany(b => b.MyFile);

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多