WebSecurity.InitializeDatabaseConnection does not interact with the first code migrations

In my project, I use the first migrations of WebSecurity and EF.

I have my own UserProfile class, which I want to combine with WebSecurity.

I want to sow users in the migration configuration class in the Seed method.

So I try this:

#1) if (!Roles.RoleExists("admin")) Roles.CreateRole("admin"); if (!WebSecurity.UserExists(AdminUserName)) WebSecurity.CreateUserAndAccount( AdminUserName, "admin", new {Email = "admin@mindmap.pl"}); 

But he complains that I must first call WebSecurity.InitializeDatabaseConnection.

Ok, that makes sense. So I added the following lines to my Global.asax:

 #2) WebSecurity.InitializeDatabaseConnection( _connectionStringName, "UserProfiles", "Id", "UserName", autoCreateTables: true); 

But than the following lines:

 #3) var dbMigrator = new DbMigrator(_configuration); dbMigrator.Update(); 

throw an error:

The database already has an object named "UserProfiles".

Well, that makes sense again as migrations try to create the table just created by WebSecurity.

I found a workaround: I placed # 2) right on top of # 1). How it worked.

  • Migrations created UserProfiles table
  • WebSecurity is connected to an existing UserProfiles table and created the other tables it needs.
  • Seeds work as they find the required tables and initialize WebSecurity.

The problem is that I had to initialize WebSecurity inside the seed method, which is smelly.

My question is how to move WebSecurity.InitializeDatabaseConnection back to Global.asax?

+1
c # entity-framework asp.net-mvc-4 code-first-migrations
Oct 06 '13 at 21:32
source share
1 answer

you can write this code in Global.asax :

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

then for sowing using migration, you will do this, here you can put your custom fields, such as email, ...:

 private void SeedMemberShip() { if (!WebMatrix.WebData.WebSecurity.Initialized) WebSecurity.InitializeDatabaseConnection(_connectionStringName, "UserProfile", "UserId", "UserName", autoCreateTables: true); var roles = (SimpleRoleProvider)Roles.Provider; var membership = (SimpleMembershipProvider)Membership.Provider; if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (membership.GetUser(username, false) == null) { membership.CreateUserAndAccount(username, password); } if (!roles.GetRolesForUser(username).Contains("Admin")) { roles.AddUsersToRoles(new[] { username }, new[] { "Admin" }); } } 

then the method call above is the seed method:

 protected override void Seed(YourContext context) { SeedMemberShip(); } 
+4
07 Oct '13 at 6:37
source share



All Articles