6

I am trying to seed users and roles with Code First Migration and OWIN Identity 2 with MVC5. I had this working before upgrading to 2.0.

First, the following works when using the non code first migration example for DropCreateDatabaseIfModelChanges

The ApplicationDbInitializer Class from the 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";

        //Create Role Admin if it does not exist
        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);
        }

        // Add user admin to Role Admin if not already added
        var rolesForUser = userManager.GetRoles(user.Id);

        if (!rolesForUser.Contains(role.Name)) 
        {
            var result = userManager.AddToRole(user.Id, role.Name);
        }
    }
}

I moved InitializeIdentityForEF code into my configuration.cs file and added these two references and project builds successfully.

using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;

But I get the following error when I run update-database from the Package Manager Console:

System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.HttpContextExtensions.GetOwinEnvironment(HttpContext context) at System.Web.HttpContextExtensions.GetOwinContext(HttpContext context)

Update

Per OdeToCode comment, you cannot use OWIN Package Manager Console: Look at line 51 here: raw.githubusercontent.com/OdeToCode/MVC5_Samples/master/… I don't think you'll have success using Owin in the Seed method unless you are running Seed from inside the app. Owin won't be around or configured if you run Seed from the package manager console. – OdeToCode May 13 at 15:00

This solution has promise but the build has the following error:

Error 4 The type 'Foo.Models.ApplicationUser' cannot be used as type parameter 'TUser' in the generic type or method 'Microsoft.AspNet.Identity.EntityFramework.UserStore'. There is no implicit reference conversion from 'Foo.Models.ApplicationUser' to '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");
}
Community
  • 1
  • 1
Barry MSIH
  • 3,525
  • 5
  • 32
  • 53

2 Answers2

0

news from the better late than never edition... if you replace

var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);

with

var userManager = new ApplicationUserManager(new UserStore(context));

everything should work. I noticed

Marc Ziss
  • 659
  • 6
  • 10
0

In my case what worked was the idea given here:

http://www.codeproject.com/Articles/674760/Code-First-Migration-and-Extending-Identity-Accoun

I replaced this piece of code in the Seed method:

        var userManager = HttpContext
            .Current.GetOwinContext()
            .GetUserManager<ApplicationUserManager>();

        var roleManager = HttpContext.Current
            .GetOwinContext()
            .Get<ApplicationRoleManager>();

with this one:

        var conText = new ApplicationDbContext();
        var userStore = new UserStore<ApplicationUser>(conText);
        var userManager = new UserManager<ApplicationUser>(userStore);

        var roleStore = new RoleStore<IdentityRole>(conText);
        var roleManager = new RoleManager<IdentityRole>(roleStore);
Ionna
  • 223
  • 4
  • 19