简体   繁体   English

UserManager.CreateAsync 不生成 Id

[英]UserManager.CreateAsync does not generate Id

I just upgraded my MVC 5 application (was previously MVC 3 with SimpleMembership ) to ASP.NET Identity 2.0 and I can work with existing users, but when I execute the following to create a new user:我刚刚将我的 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);

I get the following:我得到以下信息:

System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. System.Data.Entity.Core.UpdateException:更新条目时出错。 See the inner exception for details.有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'MyDB.dbo.AspNetUsers'; ---> System.Data.SqlClient.SqlException: 无法将值 NULL 插入到列“Id”、表“MyDB.dbo.AspNetUsers”中; column does not allow nulls.列不允许空值。 INSERT fails.插入失败。 The statement has been terminated.该语句已终止。

Does anyone have an idea why this is happening?有谁知道为什么会这样?

This is my UserManager :这是我的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"));
}

I use int keys for the users and roles, but I had the default string -keys before and there the Id was also not filled and I got a similar error.我对用户和角色使用int键,但我之前有默认的string -keys 并且那里Id也没有填充,我得到了类似的错误。

I found the problem:我发现了问题:
Because I changed the key from string to int the following migration was created:因为我将键从string更改为int所以创建了以下迁移:

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

There it correctly generated identity: true , BUT MSSQL can't convert an existing column to an identity column => the column became a "normal INT column".在那里它正确生成了identity: true ,但是 MSSQL 无法将现有列转换为标识列 => 该列变成了“普通的INT列”。
Identity must then asume that the column is an identity column and inserts null as the key and expects the DB to generate the id => exception. Identity 然后必须假设该列是一个身份列并插入null作为键,并期望 DB 生成 id => 异常。

The solution was to revert back to my SimpleMembership DB from an old backup and directly convert it to ASP.NET Identity using the int -key when creating the AspNetUsers -table.解决方案是从旧备份恢复到我的SimpleMembership数据库,并在创建AspNetUsers表时使用int键直接将其转换为ASP.NET Identity

PS: But I still don't know why I had similar problems with string -keys, but I like the int -keys better anyhow... PS:但我仍然不知道为什么我在string -keys 上遇到了类似的问题,但无论如何我更喜欢int -keys ......

Just ran into this issue, and it wasn't immediately clear to me what to do to solve it while keeping the migrations, so I'm adding this answer as a further clarification to what @ChrFin mentioned in his comment.刚刚遇到这个问题,我并没有立即清楚在保持迁移的同时如何解决它,所以我添加了这个答案作为对@ChrFin 在他的评论中提到的内容的进一步澄清。

If you switched to Int Id from Guid through a migration, this is what you have to modify in the given migration to create tables on which UserManager.Create() won't fail:如果您通过迁移从Guid切换到Int Id,这就是您必须在给定迁移中修改以创建UserManager.Create()不会失败的表的内容:

//AlterColumn("dbo.AspNetRoles", "Id", c => c.Int(nullable: false, identity: true));
DropColumn("dbo.AspNetRoles", "Id");
AddColumn("dbo.AspNetRoles", "Id", c => c.Int(nullable: false, identity: true));

// ...

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

Additional information on the correction needed, to answer a comment:有关所需更正的其他信息,以回答评论:

These modifications go in the Up() method of the auto-generated migration file.这些修改包含在自动生成的迁移文件的Up()方法中。 Basically, if you have this issue, you should be able to find the commented line AlterColumn("dbo.AspNetRoles", "Id", c => c.Int(nullable: false, identity: true));基本上,如果你有这个问题,你应该能够找到注释行AlterColumn("dbo.AspNetRoles", "Id", c => c.Int(nullable: false, identity: true)); (or the equivalent thereof), if you search for it in your solution. (或其等价物),如果您在您的解决方案中搜索它。

The migration file's Up() method will contain other lines/operations too, but they can be left as is, and only the above two needs to be overridden.迁移文件的Up()方法也会包含其他行/操作,但它们可以保持原样,只需要覆盖以上两个。

I'm actually not been working with ASP.NET MVC for a while (switched to Core), but from what I can recall, the migrations can be executed with the Updade-Database command in the Package Manager command line.我实际上有一段时间没有使用 ASP.NET MVC(切换到 Core),但据我Updade-Database ,可以使用包管理器命令行中的Updade-Database命令执行迁移。

But , of course, first you have to roll back the last migration (the unmodified one, that caused the problem).但是,当然,首先您必须回滚上次迁移(未修改的迁移,导致问题)。 From what I can recall, rolling back to a previous migration is done with the Update-Database -TargetMigration:"migration_name" command, where migration_name is the name of the preceding, still good migration.据我Update-Database -TargetMigration:"migration_name" ,回滚到以前的迁移是使用Update-Database -TargetMigration:"migration_name"命令完成的,其中migration_name是前面的名称,仍然是好的迁移。

I had this same problem after switching to int Id from Guid (random string) but I was able to solve it in a different way.从 Guid(随机字符串)切换到 int Id 后,我遇到了同样的问题,但我能够以不同的方式解决它。 I was able to use the SQL Server Object Explorer (SSOE).我能够使用 SQL Server 对象资源管理器 (SSOE)。 I opened the SSOE, found my database and expanded the tables, and right-clicked dbo.AspNetUsers >View Designer.我打开 SSOE,找到我的数据库并展开表,然后右键单击 dbo.AspNetUsers > View Designer。 I saw that Id was an int, which I thought was correct but actually it should be uniqueIdentifier.我看到 Id 是一个 int,我认为这是正确的,但实际上它应该是 uniqueIdentifier。 I tried to change the data type to uniqueIdentifier but could not.我试图将数据类型更改为 uniqueIdentifier 但不能。 When I clicked Update it was unsuccessful, it gave me an error message about it being referenced as a foreign key in other tables.当我单击“更新”失败时,它给了我一条错误消息,说明它在其他表中被引用为外键。 It listed 3 tables I think, and if you follow the trail it leads to the table dbo.AspNetUserClaims .它列出了我认为的 3 个表,如果您按照路径进行操作,它会指向表dbo.AspNetUserClaims aspNetUserClaims designer aspNetUserClaims 设计器

aspNetUserClaims 设计器

If you change the UserId field here to uniqueIdentifier it will cascade and change the data type in the other tables as well, all the way back to AspNetUsers.如果您将此处的 UserId 字段更改为 uniqueIdentifier,它将级联并更改其他表中的数据类型,一直回到 AspNetUsers。

aspNetUserClaims uniqueIdentifier

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UserManager.CreateAsync不会在ApplicationUser中保存添加的属性 - UserManager.CreateAsync does not save added properties in ApplicationUser 等待 UserManager.CreateAsync 寻找不存在的列 - await UserManager.CreateAsync looking for column that does not exist ASP.Net.Core userManager.CreateAsync - ASP.Net.Core userManager.CreateAsync 名称不能为null或为空:_userManager.CreateAsync - Name cannot be null or empty: _userManager.CreateAsync UserManager.CreateAsync。成功总是返回false - UserManager.CreateAsync .Success always returns false 正在使用的错误案例列表_userManager.CreateAsync(user,password) - List of error cases in use _userManager.CreateAsync(user, password) UserManager.CreateAsync(用户,密码)陷入无限循环 - UserManager.CreateAsync(user, password) stuck in infinite loop Foo在UserManager.CreateAsync上的关系栏错误上的角色冲突更改 - Conflicting changes to the role of Foo on relationship Bar error on UserManager.CreateAsync 如何删除使用UserManager.CreateAsync创建的用户 - How to delete users that were created with UserManager.CreateAsync Asp .Net Core 单元测试模拟 UserManager.CreateAsync 并返回标识结果 - Asp .Net Core Unit Test Mock UserManager.CreateAsync and return Identity Result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM