我正在将用户迁移到AspNet.Identity模式。我必须使用基于int的主键。我希望将用户从旧表迁移到新的Aspnet.Users表,以便在同一记录的新表中也使用旧的主键值。
为此,我启用了Identity_Insert,但UserManager忽略了它。是否可以使用基于int的PK-s并让UserManager将预定义的值插入标识列?
这就是我迄今尝试过的:
static void Main(string[] args)
{
AppContext appctx = new AppContext();
IdUserStore store = new IdUserStore(appctx);
IdUserManager manager = new IdUserManager(store);
DbContextTransaction t = appctx.Database.BeginTransaction();
appctx.Database.ExecuteSqlCommand("SET Identity_INSERT dbo.AspNetUsers ON");
IdUser u = new IdUser()
{
//id is set, UserManagerManager ignores this values in the insert
Id = 123,
UserName = "examplename",
Email = "hello@example.com"
};
IdentityResult r = manager.CreateAsync(u).Result;
t.Commit();
}抛出的异常显示:
必须为表“AspNetUsers”中的标识列指定显式值,无论是在将IDENTITY_INSERT设置为ON时还是当复制用户插入非复制标识列时。
这是生成的that,它缺少IdUser对象上存在的Id值:
INSERT [dbo].[AspNetUsers]([Email], [EmailConfirmed], [PasswordHash], [SecurityStamp], [PhoneNumber], [PhoneNumberConfirmed], [TwoFactorEnabled],[LockoutEndDateUtc], [LockoutEnabled], [AccessFailedCount], [UserName])
VALUES (@0, @1, NULL, @2, NULL, @3, @4, NULL, @5, @6, @7)
SELECT [Id]
FROM [dbo].[AspNetUsers]
WHERE @@ROWCOUNT > 0 AND [Id] = SCOPE_IDENTITY()发布于 2015-07-05 13:22:25
您必须指示,Id属性不是由DB生成的,可以从代码中设置。
您可以在映射中混淆它,如下所示:
Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 或者,如果您使用声明式方式,则将DatabaseGenerated属性添加到Id属性中:
[DatabaseGenerated(DatabaseGeneratedOption.None)]迁移所有数据后,删除此配置以恢复DB中的默认Id生成。
https://stackoverflow.com/questions/31228073
复制相似问题