Initialize database with Entity Framework 6 Code First ef-code-first entity-framework-6


What is the equivalent of these lines EF5 with SimpleMembershipProvider:

if (!WebMatrix.WebData.WebSecurity.Initialized)
    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

In EF6 with ASP.NET-Identity?

Those lines come from the global.asax file in the method protected void Application_Start().

2/10/2014 12:01:30 AM

Accepted Answer

The Entity Framework implementation of ASP.NET Identity uses Code First to create mappings and initialize the database. It simply uses standard EF Code First to initialize the database, so there isn't really the equivalent code that was referenced above (they're actually calls to the Simple Membership API, not EF).

When the ApplicationDbContext is first accessed (in the default MVC template, this happens in the AccountController), EF runs the context's initializer. By default, it uses the CreateDatabaseIfNotExists initializer, which checks to see if the tables are created and creates them if needed.

The Simple Membership call specifies the name of the connection string to use. In ASP.NET Identity, this is set in the constructor of ApplicationDbContext (in IdentityModels.cs).

The Simple Membership InitializeDatabaseConnection() method also takes in parameters for the table and column names. IdentityDbContext (which ApplicationDbContext inherits from) includes some default mappings to map to tables that are prefixed with "AspNet". You should be able to change them by overriding OnModelCreating() in ApplicationDbContext and supplying custom mappings.

And because it's just EF Code First, you can also create your own custom database initializer where you can supply a Seed() method that adds some initial roles and users, for example.

2/10/2014 7:08:00 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow