You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将IdentityUser主键从string改为GUID后UserManager失效问题

IdentityUser切换GUID主键后UserManager.FindByIdAsync返回null问题

近期将IdentityUser的唯一标识符从string改为GUID,数据库迁移已完成,但UserManager相关方法出现异常。通过DbContext的DataContext.Users.SingleAsync(...)可以正常根据邮箱查询到用户,但调用UserManager.FindByIdAsync(...)始终返回null。

相关代码实现

ApplicationUser 定义

public class ApplicationUser : IdentityUser<Guid>
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override Guid Id { get; set; }
}

DbContext 定义

public class DataContext :
    IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid, IdentityUserClaim<Guid>, IdentityUserRole<Guid>, IdentityUserLogin<Guid>, IdentityRoleClaim<Guid>, IdentityUserToken<Guid>>,
    IDataContext
{
    private readonly IUserContextAccessor _userContextAccessor;

    public DataContext(DbContextOptions<DataContext> options, IUserContextAccessor userContextAccessor) : base(options)
    {
        _userContextAccessor = userContextAccessor;
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

ProfileService 实现(错误出现在IsActiveAsync方法内)

public class ProfileService : IProfileService
{
    private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
    private readonly UserManager<ApplicationUser> _userManager;

    public ProfileService(
        UserManager<ApplicationUser> userManager,
        IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory)
    {
        _userManager = userManager;
        _claimsFactory = claimsFactory;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        ...
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        context.IsActive = user != null;
    }
}

服务注册代码

services.AddIdentity<ApplicationUser, IdentityRole<Guid>>(options =>
            {
                options.User.RequireUniqueEmail = true;
            })
            .AddEntityFrameworkStores<DataContext>()
            .AddDefaultTokenProviders();

内容的提问来源于stack exchange,提问作者qqqqqkks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 16:22:35