Reputation: 419
Using Identity 2.0 in an MVC application, VS 2013. I want to extend some of the built in tables used by the membership system, and add new ones. The former works well. In IdentityModels.cs if I add some new properties to ApplicationUser, then these changes automaticaly get migrated to the AspNetUsers table. As far as I can tell, this is set up by the static constructor for ApplicationDBContext which inherits from IdentityDbContext, and the DbInitializer is based on DropCreateDatabaseIfModelChanges. So any changes to ApplicationUser will cause the database to be dropped and recreated - exactly what I want.
What also works, though I don't understand why, is if I want to add something to the ASPNetRoles table, such as a description, I can do that by creating a class which inherits from IdentityRole, adding the new property there, and changing ApplicationRoleManager to wor with my new Role sub class. If I make any changes in this new class, these are also migrated to the database. How does that happen? And what's this Discriminator field it adds all about?
My real question is this - and I suspect I don't know the answer because I am not sure how these other migrations are working - how can I add new tables to the standard 5 which Identity 2.0 uses - and have these both initially created and migrated when changed? DO i Have to use the package manager and add migrations for these new tables, or can I get them automatically migrated as the others?
Thanks
Ray
Upvotes: 0
Views: 999
Reputation: 37520
If you use the Object Browser to take a look at the class IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>
, you can see that it has an IDbSet<TRole> Roles
. The role type you pass to ApplicationRoleManager
trickles down to here and that's how EF knows about your new class.
The Discriminator column is something EF creates by default when Table per Hierarchy (TPH) is in use. It enables EF to distinguish between the different types that are stored in the same table.
To add tables to the ApplicationDbContext
, you simply have to create DbSet
s for them. For instance...
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer<ApplicationDbContext>(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());
}
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
}
Because the DropCreateDatabaseIfModelChanges
intializer is used, the database should be wiped and updated whenever the model changes.
Upvotes: 1