在 AspNetRoles 表中设置 ConcurrencyStamp 的值是多少

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

我需要添加一些用户角色作为数据迁移脚本的一部分。

ConcurrencyStamp
似乎是一个 GUID。有谁知道这里是否需要一些特殊的东西?或者我可以添加任何 GUID 值吗?

c# asp.net asp.net-core asp.net-identity
1个回答
0
投票

迁移数据时,您可以在ConcurrencyStamp字段中添加GUID值,但需要确保它在数据库中是唯一的。并且需要注意的是,如果实体被修改,则ConcurrencyStamp的值需要更新。您可以创建一个

SaveChangesInterceptor
来自动更新 ConcurrencyStamp。这是一个例子供您参考:

public class ConcurrencyStampInterceptor : SaveChangesInterceptor
{
    public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
    {
        UpdateConcurrencyStamps(eventData.Context);
        return base.SavingChanges(eventData, result);
    }

    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
    {
        UpdateConcurrencyStamps(eventData.Context);
        return base.SavingChangesAsync(eventData, result, cancellationToken);
    }

    private void UpdateConcurrencyStamps(DbContext context)
    {
        if (context == null) return;

        foreach (var entry in context.ChangeTracker.Entries<IdentityRole>())
        {
            if (entry.State == EntityState.Modified || entry.State == EntityState.Added)
            {
                entry.Entity.ConcurrencyStamp = Guid.NewGuid().ToString();
            }
        }

        foreach (var entry in context.ChangeTracker.Entries<IdentityUser>())
        {
            if (entry.State == EntityState.Modified || entry.State == EntityState.Added)
            {
                entry.Entity.ConcurrencyStamp = Guid.NewGuid().ToString();
            }
        }
    }
}

当我更改角色名称时:

public async Task UpdateRoleNameAsync(string oldRoleName , string newRoleName)
{
     var role = await _context.Roles.SingleOrDefaultAsync(r => r.Name == oldRoleName);

     if (role != null)
     {
               
         role.Name = newRoleName;
         role.NormalizedName = newRoleName.ToUpper();
         await _context.SaveChangesAsync();
     }
     else
     {
         throw new InvalidOperationException($"Role '{oldRoleName}' not found.");
     }
}

相关GUID已更改:

enter image description here enter image description here

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