c# - SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“AspNetUsers”中插入标识列的显式值
问题描述
我已使用 Microsoft.AspNet.Identity 的启用迁移将 aspnetuser 表列数据类型字符串更改为 long。
使用以下迁移脚本成功创建表:
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.Long(nullable:false,identity:true),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
FullName = c.String(nullable: false, maxLength: 50),
CreatedBy = c.Long(nullable: true),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(nullable: false, defaultValue: null, defaultValueSql: null),
ModifiedBy = c.Long(nullable: true),
IsDeleted = c.Boolean(nullable: false, defaultValue: false, defaultValueSql: "0")
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
但是,当我尝试使用以下代码创建用户时,出现错误为“SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'AspNetUsers' 中插入标识列的显式值”。
// first we create Admin rool
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = SuperAdminRole;
roleManager.Create(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "Admin";
user.Email = "xyz@gmail.com";
user.FullName = "xyz";
user.IsDeleted = false;
user.ModifiedBy = null;
user.ModifiedDate = null;
user.CreatedBy = string.Empty;
user.CreatedDate = DateTime.Now;
string userPWD = "admin_123";
var chkUser = UserManager.Create(user, userPWD);
如果有人对此有解决方案,请分享。
感谢您的快速回复!
解决方案
我相信 IDENTITY_INSERT 是自动增量功能,它设置为 OFF。因此,验证字段“Id”是 sql 数据库中的标识列,并在代码优先实体框架的“Id”列中添加以下属性
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
推荐阅读
- sql - TSQL:获取每小时的销售数据
- unity3d - Graphics.Blit uv 信息是如何传递的?
- python - TF 中的索引操作
- python - Scrapy 使用 crawlerprocess 运行时抛出错误
- javascript - 为什么 Flow 不支持详尽检查中的常量?
- python - Flask TypeError:“str”和“int”的实例之间不支持“<”
- c - 使用用户定义函数的帕斯卡三角形的替代方法
- google-apps-script - 有没有一种干净的方法可以将稀疏网格写入谷歌表格范围
- rust - 如何获得 tokio::fs::File::open 的静态路径?
- docker - gcloud 集群无法提取 eu.gcr.io 所需的身份验证