Reputation: 6618
I'm trying to get Membership roles being created in my SQL Azure database using ASP.NET MVC 4 and Entity Framework 5. I can get this to work just fine on my local host, but it doesn't seem to create the accounts nor the membership roles on Azure. Note that I'm also using Fluent NHibernate but I believe this is unrelated.
In my Application_Start() function I initialize the database to make sure all the tables exist:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
I also created a SeedMembership() function (called by the Seed() function in Migrations\Configuration.cs) that looks like this:
private void SeedMembership()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
if (!roles.RoleExists("Administrator"))
{
roles.CreateRole("Administrator");
}
if (membership.GetUser("TestAccount", false) == null)
{
membership.CreateUserAndAccount("TestAccount", "testpwd");
}
if (!roles.GetRolesForUser("TestAccount").Contains("Administrator"))
{
roles.AddUsersToRoles(new[] { "TestAccount" }, new[] { "Administrator" });
}
}
Using update-database in the package manager console I can see that the Seed method is being called. I even ran this command using the actual SQL Azure connection string:
PM> Update-Database -StartUpProjectName "MyProject" -ConnectionString "Data Source=tcp:myDB.database.windows.net,1433;Initial Catalog=myDB;User Id=myUser@myDB;Password=myPwd" -ConnectionProviderName "System.Data.SqlClient"
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying code-based migrations: [201212251057032_Initial].
Applying code-based migration: 201212251057032_Initial.
Running Seed method.
PM>
But even like this my "Administrator" account is not created. I know because I added a check in my view:
@if(User.IsInRole("Administrator"))
{
<li>@Html.ActionLink("Admin", "Index", "Admin")</li>
}
And the "Admin" link never shows up when trying on Azure, but works just fine locally.
Is there a way for me to troubleshoot what's going on? Am I even trying this correctly?
Upvotes: 3
Views: 1031
Reputation: 6618
After a couple of days of troubleshooting and hair-pulling, I got this to work. I fixed it by adding the check from SeedMembership() in App_Start(). According to the Interweb and Visual Studio, the Seed() function is called upon deployment but that's not what I've seen.
Upvotes: 2