I am trying to separate users and roles using First First Migration and OWIN Identity 2 with MVC5. I had this before upgrading to 2.0.
First, the following works when using the first codeless migration example for DropCreateDatabaseIfModelChanges
Class ApplicationDbInitializer from IdentityConfig.cs file:
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
var userManager = HttpContext
.Current.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current
.GetOwinContext()
.Get<ApplicationRoleManager>();
const string name = "admin@admin.com";
const string password = "Admin@123456";
const string roleName = "Admin";
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
}
I translated the InitializeIdentityForEF code into my configuration.cs file and successfully added these two links and project assemblies.
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
But when starting the update database from the package manager console, the following error appears:
System.NullReferenceException: . System.Web.HttpContextExtensions.GetOwinEnvironment( HttpContext) System.Web.HttpContextExtensions.GetOwinContext( HttpContext)
OdeToCode OWIN:
51 : raw.githubusercontent.com/OdeToCode/MVC5_Samples/master/... , Owin Seed, Seed . Owin , Seed . - OdeToCode 13 15:00
, :
4 "Foo.Models. ApplicationUser" "TUser" "Microsoft.AspNet.Identity.EntityFramework.UserStore". "Foo.Models.ApplicationUser" "Microsoft.AspNet.Identity.EntityFramework.IdentityUser". c:\foo\Migrations\Configuration.cs 86 43
protected override void Seed(Repository.DataContext.IdentityDb context)
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser { UserName = "sallen" };
userManager.Create(user, "password");
roleManager.Create(new IdentityRole { Name = "admin" });
userManager.AddToRole(user.Id, "admin");
}