ASP.NET Identity - What method creates the tables?

2k views Asked by At

When you create a new MVC5 project in VS2013 with Individual User Accounts, the account tables (dbo.AspNet*) are created automatically in the database defined by the DefaultConnection the first time you try to log in or register a new account. Does anyone know the exact class/method in the project that creates these tables?

With SimpleMembership in VS2012 / MVC4, the tables were created using this method:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

which is called in the SimpleMembershipInitializer class of the InitializeSimpleMembershipAttribute.cs filter.

I have not been able to find a similar method in a VS2013 / MVC5 project.

Any clues?

2

There are 2 answers

2
Hao Kung On

By default, the MVC5 template relies on EntityFramework CodeFirst's default database initializer to create the database the first time its needed.

See CreateDatabaseIfNotExists

1
Oskar Lindberg On

Have a look at the DbContext (System.Data.Entity), inherited by IdentityDbContext (Microsoft.AspNet.Identity.EntityFramework), inherited by ApplicationDbContext that you will find inside the IdentityModels.cs in the default Visual Studio 2013 ASP.NET Web Application/MVC template.

The AccountController gives you a clue as to how the above gets into play in how it is initialized:

public AccountController()
        : this(new UserManager<ApplicationUser>(
              new UserStore<ApplicationUser>(new ApplicationDbContext()))) {}

(If, by any chance, you're looking to customize, Kevin is right in his comment. For example, properties can be easily added to User through the ApplicationUser, and more control can be achieved as usual by your own implementation of whatever. The old identity and authentication architecture has been completely replaced by OWIN/Katana.)

EDIT: Actually, I might have slightly misread your question. The code that actually creates the data base if need be probably resides in something like the CreateDatabaseIfNotExists class (System.Data.Entity). I'm not sure which exact implementation gets called from which context, but obviously creating the DB is the responsibility of Entity Framework.

Still, using dotPeek, ILSpy, ReSharper or something similar, you should be able to find what you're looking for if you start out exploring the classes I mentioned initially. (The suggestion that this is not the place to alter behavior still stands.)

Hope this helps.