MVC 4 Asp.net Simple Membership Provider and Entity Framework Migrations

So I have spent about 5-6 hours trying to figure out how to get EF Migrations working properly with MVC 4 when you are using the Seed method to insert initial data into your tables.

The issue is that when you enter some methods like this:

if (!Roles.RoleExists("Admin"))
{
  Roles.CreateRole("Admin");
}
 
if (Membership.GetUser("username", false) == null)
{
  WebSecurity.CreateUserAndAccount("username", "password");
  Roles.AddUserToRole("username", "Admin");
}
 
if (!Roles.IsUserInRole("username", "Admin"))
{
  Roles.AddUserToRole("username", "password");
}

Which is how most older examples which are available on the internet tell you to do it. The problem is when you try and use this with code migrations you get:

You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.

So if you take and add this:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

To your seed method, you get this:

To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".

So the key to fixing that is that even though the built in forms authentication doesn’t use the settings in the web config (and will actually ignore it), you need to put some settings in there for EF Migrations to be configured properly.

So we add to the System.Web area of the Web.Config:

<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
  <providers>
    <clear/>
    <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
  </providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
  <providers>
    <clear/>
    <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" requiresQuestionAndAnswer="false" />
  </providers>
</membership>

And rerun the update-database command. It works now.

I hope this helps someone else to not spend all the time I was spending.

Tags: ,

Thursday, April 25th, 2013 Development

1 Comment to MVC 4 Asp.net Simple Membership Provider and Entity Framework Migrations

  • Steven Goodson says:

    This helped me tremendously! I needed to add it to my seed method. Thank you so much!

  • Leave a Reply to Steven Goodson