.net 为什么UserManager不将用户保存到数据库

j8yoct9x  于 2023-03-04  发布在  .NET
关注(0)|答案(1)|浏览(107)

我试着自己解决这个问题,并尝试了许多可能的方法。
问题是-当我使用UserManager.CreateAsync(user, request.Password),然后使用_context.SaveChangesAsync()时,没有记录添加到表中。并且_context.SaveChangesAsync()返回0,这意味着没有记录受到影响
但在使用CreateAsync创建用户,然后使用此_context.Users.AddAsync(user)添加并调用**SaveChangesAsync()**后,所有内容都将保存。
PS. user.Id具有值,SaveChangesAsync和CreateAsync上没有异常,我已尝试尝试捕获这些位置
下面是我目前正在使用的代码。

应用程序数据库上下文.cs

public class ApplicationDbContext : IdentityDbContext<User>, IApplicationDbContext
    {

        public ApplicationDbContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<ExternalApplications> Applications { get; set; }

        public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            return await base.SaveChangesAsync(cancellationToken);
        }
    }

持久性DI.cs

public static class PersistenceDI
{
    public static IServiceCollection AddPersistenceLayer(this IServiceCollection services, string connectionString)
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

        services.AddIdentityCore<User>().AddEntityFrameworkStores<ApplicationDbContext>().AddUserManager<UserManager<User>>();

        services.AddScoped<IUserRepository, UserRepository>();

        return services;
    }
}

用户.cs

public class User : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

创建用户命令处理程序.cs

public record CreateuserCommand : IRequest<string>
    {
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class CreateUserCommandHandler : IRequestHandler<CreateuserCommand, string>
    {
        public IApplicationDbContext _context;
        public UserManager<User> _userManager;

        public CreateUserCommandHandler(IApplicationDbContext context, UserManager<User> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        public async Task<string> Handle(CreateuserCommand request, CancellationToken cancellationToken)
        {
            User user = new User
            {
                Email = request.Email,
                FirstName = request.FirstName,
                LastName = request.LastName,
                UserName = request.FirstName + " " + request.LastName + "eqweetwtweywe",
            };

            await _userManager.CreateAsync(user, request.Password);
            await _context.SaveChangesAsync(cancellationToken);

            return user.Id;
        }
    }
w6lpcovy

w6lpcovy1#

我设法修复了这个问题,try catch块没有捕获错误。_userManager.CreateAsync()返回IdentityResult,当我检查它时,用户名有错误。

相关问题