【问题标题】:SqlException with Creating User, after changing IdentityUser primary key from string to int在将 IdentityUser 主键从字符串更改为 int 后,创建用户时出现 SqlException
【发布时间】:2018-02-07 09:13:36
【问题描述】:

在我按照this 将应用程序用户 ID 的类型从字符串更改为 int 后,如果我尝试创建新用户,则会收到 SqlException。

确切的错误是:

无法将值 NULL 插入到列“Id”表“DBNAME.dbo.AspNetUsers”中;列不允许空值。插入失败。声明已终止。

Line 208:                };
Line 209:
Line 210:                var result = await UserManager.CreateAsync(user, model.Password);
Line 211:                if (result.Succeeded)
Line 212:                {

Source File: C:\Projects\ProjectName\ProjectName\Controllers\MembersController.cs    Line: 210 

[SqlException (0x80131904): Cannot insert the value NULL into column 'Id', table 'DBNAME.dbo.AspNetUsers'; column does not allow nulls. INSERT fails.
The statement has been terminated.]

这是 AspNetUsers 表设计视图的截图:

我看过How to tell the primary key 'Id' of IdentityUser class is IDENTITY(1,1)?ASP.NET Identity - Error when changing User ID Primary Key default type from string to int AND when using custom table names 但对我帮助不大。

非常感谢任何帮助。

【问题讨论】:

    标签: asp.net entity-framework asp.net-identity


    【解决方案1】:

    Identity 不再为您生成密钥的问题 - 以前发生过。

    要解决这个问题,您需要获取由数据库自动生成的密钥。要完成此操作,您需要在 Id 类中的 Id 属性上应用以下属性:

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override int Id { get; set; }
    

    并添加另一个 DB-migration 以确保数据库知道如何处理此字段。

    UPD:哎呀。刚刚注意到您已经链接到我的相同答案。这没有帮助吗?

    【讨论】:

    • 我也做了同样的事情,但没有任何好处,迁移文件也显示为空。
    • 迁移在这里可能是个问题。我记得我必须删除并重新创建迁移表才能接受此更改。尝试this method 使您的Id 列变为Identity(1,1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2014-06-28
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多