[英]SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF
[英]SqlException: Cannot insert explicit value for identity column in table 'AspNetUsers' when IDENTITY_INSERT is set to OFF
我已使用Microsoft.AspNet.Identity的enable-migration將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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.