gpt4 book ai didi

c# - UserManager.CreateAsync 不生成 Id

转载 作者:行者123 更新时间:2023-11-30 14:30:08 28 4
gpt4 key购买 nike

我刚刚将我的 MVC 5 应用程序(以前是带有 SimpleMembership 的 MVC 3)升级到 ASP.NET Identity 2.0,我可以使用现有用户,但是当我执行以下命令创建新用户时:

var user = new ApplicationUser();
//user.Id = db.Users.Max(u => u.Id) + 1; //does not help
user.UserName = model.UserName;
user.Email = model.EMailAddress;
var result = await UserManager.CreateAsync(user, model.Password);

我得到以下信息:

System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'MyDB.dbo.AspNetUsers'; column does not allow nulls. INSERT fails. The statement has been terminated.

有人知道为什么会这样吗?

这是我的 UserManager:

var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<MyDbContext>()));

manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};

manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};

manager.EmailService = new EmailService();

var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
}

我为用户和角色使用 int 键,但我之前有默认的 string-keys 并且 Id 也没有填充,我得到了类似的错误。

最佳答案

我发现了问题:
因为我将 key 从 string 更改为 int,所以创建了以下迁移:

AlterColumn("dbo.AspNetUsers", "Id", c => c.Int(nullable: false, identity: true));

在那里它正确生成了 identity: true,但是 MSSQL 无法将现有列转换为标识列 => 该列变成了“普通 INT 列”。
Identity 必须假定该列是一个标识列并插入 null 作为键并期望 DB 生成 id => 异常。

解决方案是从旧备份恢复到我的 SimpleMembership 数据库,并使用 int 将其直接转换为 ASP.NET Identity - 创建 AspNetUsers 表时的键。

P.S.: 但我仍然不知道为什么我在使用 string-keys 时遇到了类似的问题,但无论如何我更喜欢 int-keys...

关于c# - UserManager.CreateAsync 不生成 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24272478/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com