c# - WebSecurity.InitializeDatabaseConnection doesn't cooperate with code first migrations -


in project use websecurity , ef code first migrations.

i have custom userprofile class want combine websecurity.

i want seed users in migrations' configuration class in seed method.

so try this:

#1) if (!roles.roleexists("admin"))             roles.createrole("admin");  if (!websecurity.userexists(adminusername))     websecurity.createuserandaccount(         adminusername,         "admin",         new {email = "admin@mindmap.pl"}); 

but complains should call websecurity.initializedatabaseconnection first.

ok, makes sense. added following lines global.asax:

#2) websecurity.initializedatabaseconnection(     _connectionstringname,     "userprofiles",     "id",     "username",     autocreatetables: true); 

but following lines:

#3) var dbmigrator = new dbmigrator(_configuration); dbmigrator.update(); 

throw error:

there object named 'userprofiles' in database.

well, makes sense again migrations try create table that's been created websecurity.

i found out workaround: placed #2) right on top of #1). worked.

  1. migrations created userprofiles table
  2. websecurity attached existing userprofiles table , created other tables needed
  3. seeds works found needed tables , websecurity initialized.

the problem had initialize websecurity inside seed method, kind of smelly.

my question how move websecurity.initializedatabaseconnection global.asax?

you can write code in global.asax :

if (!webmatrix.webdata.websecurity.initialized)                 websecurity.initializedatabaseconnection(_connectionstringname, "userprofile", "userid", "username", autocreatetables: true); 

then seeding using migration way, here can put customized fields 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 call above method seed method :

protected override void seed(yourcontext context)         {              seedmembership();         } 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -