级联删除具有关系的实体框架标识用户



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

错误信息:

SqlException:DELETE 语句与 REFERENCE 冲突 约束"FK_Workspaces_AspNetUsers_OwnerId"。冲突发生 在数据库"我的上传"中,表"dbo。工作区",列"所有者 ID"。这 声明已终止。 Microsoft.Data.SqlClient.SqlCommand+<>c.b__164_0(Task 结果(

扩展标识:

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()
{
}
}

使用Fluent API,我设法在OnModelCreate方法中使用此代码将级联删除添加到IdentityUser。

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

最新更新