Question

Using MVC5 and EF6 I'm trying to create dummy user accounts by copying code from AccountController Register Action as below:

class SampleData : DropCreateDatabaseAlways<EFDbContext>
{
 public Microsoft.AspNet.Identity.UserManager<ApplicationUser> UserManager { get; private set; }

protected override void Seed(EFDbContext context)
    {

        base.Seed(context);
        var user = new ApplicationUser() { UserName = "Candidate1", AboutSelf = "", FirstName = "Candidate1",LastName="Candidate1",Sex=SexType.Unspecified,Id= Guid.NewGuid().ToString() };
         UserManager.CreateAsync(user, "Candidate1");
...

In above code there are few custom profile properties added and I have populated all but I still get null reference exception:

at TestPro.WebUI.SampleData.Seed(EFDbContext context) in d:\Users\Arvind\Documents\Visual Studio 2013\Projects\TestPro\TestPro.WebUI\Models\SampleData.cs:line 22
at System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse`1.<CreateInitializationAction>b__d()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Database.Initialize(Boolean force)
at TestPro.WebUI.MvcApplication.Application_Start() in d:\Users\Arvind\Documents\Visual Studio 2013\Projects\TestPro\TestPro.WebUI\Global.asax.cs:line 17
Was it helpful?

Solution

Got it, I misssed to initialize UserManager property before use

class SampleData : DropCreateDatabaseAlways<EFDbContext>
{
public Microsoft.AspNet.Identity.UserManager<ApplicationUser> UserManager { get; private set; }

protected override void Seed(EFDbContext context)
{
//Need to initialize UserManager property
UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    base.Seed(context);
    var user = new ApplicationUser() { UserName = "Candidate1", AboutSelf = "", FirstName = "Candidate1",LastName="Candidate1",Sex=SexType.Unspecified,Id= Guid.NewGuid().ToString() };
     UserManager.CreateAsync(user, "Candidate1");

...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top