Entity Framework 6、MVC5、ASP Identity 2.0。
我按照这 2 个教程创建了 Web 应用程序的登录部分:part 1 - part 2
我从另一个库项目中的 IdentityUser 类创建了自己的 AppUser 类。我也有来自 IdentityDbContext 的数据上下文
public class DataContext: IdentityDbContext<AppUser>
{
public DataContext(): base("DefaultConnection") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AppUser>().Property(u => u.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
}
}
public class AppUser : IdentityUser
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public override string Id { get; set; }
[Required]
[Display(Name ="First Name")]
[MaxLength(100)]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[MaxLength(100)]
public string LastName { get; set; }
[MaxLength(100)]
public string Title { get; set; }
[Required(ErrorMessage = "Email is required.")]
[Display(Description = "Email")]
public override string Email { get; set; }
[MaxLength(20)]
public string Phone { get; set; }
[Range(0,9999)]
[Display(Name = "Extension")]
public int PhoneExtension { get; set; }
[Display(Name = "Active")]
[DefaultValue(true)]
public bool IsActive { get; set; }
}
当我运行种子方法时,出现以下错误
System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'CRM1.dbo.AspNetUsers'; column does not allow nulls. INSERT fails. The statement has been terminated.
播种方法如下:
protected override void Seed(CRM.DAL.Data.DataContext context)
{
context.AccessLevels.AddOrUpdate(al => al.Label,
new Model.AccessLevel { AccessLevelID = 1, Label = "Admin", Description = "Full access to the CRM data" },
new Model.AccessLevel { AccessLevelID = 2, Label = "Customer Service", Description = "Full access to the CRM data" },
new Model.AccessLevel { AccessLevelID = 3, Label = "Sales", Description = "Full access to the CRM data" }
);
if (!(context.Users.Any(u => u.UserName == "admin@admin.com")))
{
var userStore = new UserStore<AppUser>(context);
var userManager = new UserManager<AppUser>(userStore);
var userToInsert = new AppUser
{
Id = "1",
FirstName = "Admin",
LastName = "Admin",
Title = "Administrator",
Email = "admin@admin.com",
PhoneExtension = 0,
IsActive = true,
AccessLevelID = 1,
EmailConfirmed = true,
PhoneNumberConfirmed = true,
TwoFactorEnabled = false,
LockoutEnabled = false,
AccessFailedCount = 0,
UserName = "admin"
};
userManager.Create(userToInsert, "password");
}
}
所以 Id 得到一个值,但 EF 说它正在插入 NULL。我尝试过不给 Id 任何值,认为 EF 会自动执行它但没有。
用我的上下文为 AspNetUser 播种的方法是什么?我看到了不同的教程,但它不适用于我的扩展 AppUser 类和 DataContext。
谢谢
最佳答案
下面的事情发生在我身上。我按照本指南将 ASP.NET Identity 中用户的主键从 Guid 更改为 Int。
我已经进行了一些迁移,因此 EF 尝试将 Id 从 nvarchar(128) 更改为 int。这行得通,但 Identity Specification
从未从“否”变为"is"。通过删除所有以前的迁移,删除数据库然后为所有更改进行新迁移来解决它。由于我们处于早期开发阶段,这不是问题。
关于c# - MVC5 EF6 种子方法 : Cannot insert NULL into column 'Id' table AspNetUsers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856085/