Unable to add new role in Seed method after change. Identity from string to int
Following this article in "Change Primary Key for Users in ASP.NET Identity" I have a problem while adding a new role to the Seed Method.
Cannot insert NULL value into column
'Id'
, table'X.dbo.AspNetRoles'
; the column does not allow zeros. INSERT fails.
The application has been completed.
My code:
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"));
}
And the error occurs on the last line: roleManager.Create ...
Plus to the tutorial I have this implementation in 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>()));
}
}
Edit 1
public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
+3
source to share
1 answer
I can do a little work for this. You can manually update the CustomRole table in the database to have auto increment values. Then override EF OnModelCreating as described below.
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);
}
}
0
source to share