Search code examples
c#entity-frameworkasp.net-identityasp.net-identity-2

Adding a new property in Identity Framework


First, the IdentityModels.cs looked like this : using Microsoft.AspNet.Identity.EntityFramework;

namespace WebApplication2.Models
{

    public class ApplicationUser : IdentityUser
    {
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }
}

I changed this file to this :

namespace WebApplication2.Models
{

    public class ApplicationUser : IdentityUser
    {
        public string Email { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
            Database.SetInitializer<ApplicationDbContext>(new DropCreateDatabaseAlways<ApplicationDbContext>());
        }
    }
}

I also added Email to RegisterViewModel in AccountViewModel.cs.

I also changed AccountController to this :

 var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email};
                var result = await UserManager.CreateAsync(user, model.Password);

When I click register, it fails at this line :

 var result = await UserManager.CreateAsync(user, model.Password);

Saying this :

System.Data.SqlClient.SqlException: Invalid column name 'Email'. Why am I getting this error? What am I missing? Thanks.


Solution

  • open up nuget console and type:

    update-database -force
    

    before that make sure you have automatic migrations turned on. you can turn it on by doing

    enable-migrations