关注this文章到"更改ASP.NET身份用户的主键"在Seed方法中添加新角色时遇到问题。
无法将值NULL插入列
'Id'
,表'X.dbo.AspNetRoles'
;列不允许空值。 INSERT失败。
声明已经终止。
我的代码是:
protected override void Seed(ApplicationDbContext context)
{
var roleStore = new CustomRoleStore(context);
var roleManager = new ApplicationRoleManager(roleStore);
if (!roleManager.RoleExists("Administrador"))
roleManager.Create(new CustomRole("Administrador"));
}
错误发生在最后一行:roleManager.Create ...
另外在教程中我在IdentityConfig.cs中有这个实现:
public class ApplicationRoleManager : RoleManager<CustomRole, int>
{
public ApplicationRoleManager(IRoleStore<CustomRole, int> roleStore)
: base(roleStore) { }
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<CustomRole, int, CustomUserRole>(context.Get<ApplicationDbContext>()));
}
}
修改1
public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
答案 0 :(得分:0)
我可以为此付出一些努力。您可以手动更新数据库上的CustomRole表以具有自动增量值。然后覆盖EF OnModelCreating,如下所述。
public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBinder modelBinder)
{
modelBinder.Entity<CustomRole>().ToTable("CustomRole"); // This may be not needed, check it.
modelBinder.Entity<CustomRole>().Property(r => r.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}