In my project I use WebSecurity and EF code first migrations.
I have my custom UserProfile class I want to combine with WebSecurity.
I want to seed users in migrations' Configuration class in 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 it complains that I should call WebSecurity.InitializeDatabaseConnection first.
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 the error:
There is already an object named 'UserProfiles' in the database.
Well, this makes sense again as migrations try to create the table that's just been created by WebSecurity.
I found out a workaround: I placed #2) right on top of #1). Than it worked.
- Migrations created the UserProfiles table
- WebSecurity attached to the existing UserProfiles table and created other tables it needed
- Seeds works as they found the needed tables and WebSecurity was initialized.
The problem is that I had to initialize the WebSecurity inside the seed method, which is kind of smelly.
My question is how to move WebSecurity.InitializeDatabaseConnection back to Global.asax?
you can write this code in
Global.asax
:then for seeding that using migration you do that this way, here you can put your customized fields like email,... :
then call above method is seed method :