Walter Lockhart
Walter Lockhart

Reputation: 1293

ASP.NET Identity Create an Account

I am using ASP.NET MVC 5.0 EF 6.0 and Identity 1.0 to build an application.

I have a seed function which currently runs successfully and inserts various pieces of data like 'Teachers' into the database. I would like to extend the seed function so that when I create a new Teacher it also creates a new user Account in the AspNetUsers table.

I have tried the following code in the file 'SampleData.cs':

using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using Oberhofen.EdNow.Data.Models;
using Oberhofen.EdNow.Model.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;

namespace Oberhofen.EdNow.Data
{
    public class EdNowSampleData : DropCreateDatabaseIfModelChanges<EdNowEntities>
    {
        private UserManager<ApplicationUser> userManager;

        protected override void Seed(EdNowEntities context)
        {
            // Create a new Account.
            string UserName = "wallock";
            string Password = "Password";

            var user = new ApplicationUser { UserName = UserName, Email = "[email protected]" };
            var result = userManager.Create(user, Password);

            var userId = user.Id;

            // Create new Teachers.
            var teachers = new List<Teacher>
            {
                new Teacher { FirstName = "Walter", LastName = "Lockhart", PersonTypeId=2, UserId=userId }
            };
            teachers.ForEach(tchr => context.Teachers.Add(tchr));
            context.Commit();
        }
    }
}

When I run the code at line:

var result = userManager.Create(user, Password);

I get the following exception:

An exception of type 'System.ArgumentNullException' occurred in Microsoft.AspNet.Identity.Core.dll > but was not handled in user code. Value cannot be null. Parameter name: manager

Would someone please advise what I am missing in my code that could be causing this exception.

Thanks in advance.

Regards

Walter

Upvotes: 0

Views: 2006

Answers (1)

Robert P
Robert P

Reputation: 157

before you put the result you should do this:

userManager = new UserManager<ApplicationUser>(); 

or set it to null in the declaration.

Upvotes: 1

Related Questions