I have a simple aspnet Identity schema but im not able to create the tables of Identity in my Database. Heres the main classes used by the MVC website for identity:
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
EntityTypeConfiguration<ApplicationUser> table =
modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
table.Property((ApplicationUser u) => u.UserName).IsRequired();
modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) =>
new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");
EntityTypeConfiguration<IdentityUserLogin> entityTypeConfiguration =
modelBuilder.Entity<IdentityUserLogin>().HasKey((IdentityUserLogin l) =>
new
{
UserId = l.UserId,
LoginProvider = l.LoginProvider,
ProviderKey
= l.ProviderKey
}).ToTable("AspNetUserLogins");
entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin u) => u.User);
EntityTypeConfiguration<IdentityUserClaim> table1 =
modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
table1.HasRequired<IdentityUser>((IdentityUserClaim u) => u.User);
modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
EntityTypeConfiguration<IdentityRole> entityTypeConfiguration1 =
modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
entityTypeConfiguration1.Property((IdentityRole r) => r.Name).IsRequired();
}
}
When I try to login, the OnModelCreating method executes but when i go to the database the tables are not created and I get the error "Invalid Column name AspNetUsers". Whats wrong here?
To your Global.Asax add
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());
This will drop and re-create database on every model change.
Read more about Entity Framework Database Initialization Strategies