无法更新 ASP.NET Core IdentityRole 对象

问题描述 投票:0回答:1

我正在尝试更新

IdentityRole
对象,但收到
InvalidOperationException
错误。

代码

public class EditModel : PageModel
{
    private readonly RoleManager<IdentityRole> _roleManager;

    public EditModel(RoleManager<IdentityRole> roleManager)
    {
        _roleManager = roleManager;
    }

    [BindProperty]
    public IdentityRole IdentityRole { get; set; }

    public async Task<IActionResult> OnGetAsync(string id)
    {
        if (id == null)
        {
            return NotFound();
        }

        IdentityRole = await _roleManager.FindByIdAsync(id);

        if (IdentityRole == null)
        {
            return NotFound();
        }

        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        try
        {
            await _roleManager.UpdateAsync(IdentityRole); //Error is occurring here.
        }

        catch (DbUpdateConcurrencyException)
        {
            throw;
        }

        return RedirectToPage("./Index");
    }
}

错误

InvalidOperationException:无法跟踪实体类型“IdentityRole”的实例,因为已跟踪具有相同键值 {'Id'} 的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。

asp.net-core .net-core asp.net-identity razor-pages
1个回答
3
投票

我像这样更改了代码,现在它可以工作了。当我更新

IdentityRole.Name
属性时,它还会自动更新数据库中的
IdentityRole.NormalizedName
列。

var role = await _roleManager.FindByIdAsync(IdentityRole.Id);
role.Name = IdentityRole.Name;
await _roleManager.UpdateAsync(role);

我找到了解决方案这里

© www.soinside.com 2019 - 2024. All rights reserved.