Today post, I will show you how to integrate EF5 CodeFirst nicely with SimpleMembership and at the same time, seeding some of your users, roles and associating users to roles while supporting custom fields/properties during registration.

I think this is a nice to have, especially during PoC development where you could be developing features that depend on authentication and authorization while making schema changes with EF CodeFirst. The last thing you want to do is run update-database for migrations and have to manually re-insert/re-seed all your users, roles and associating the two every time you ran migrations (e.g. update-database -force from the Package Manager Console).

First, create an “Internet Application” ASP.NET MVC4 Project, because this is the only out of the box MVC template that has the new SimpleMembershipProvider wired up out of the box. One of the features I like the most about the SimpleMembershipProvider is it gives you total control of the highly requested “User” table/entity. Meaning you integrate SimpleMembershipProvider with your own user table, as long as it has a UserId and UserName fields in your table.

Explicitly wire up the providers even though this is implied, so that when do run the “update-database” command from the Package Manager Console for migrations we can use the native “Roles” Api.

In the “System.Web” Section add:

01    <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
02      <providers>
03        <clear/>
04        <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
05      </providers>
06    </roleManager>
07    <membership defaultProvider="SimpleMembershipProvider">
08      <providers>
09        <clear/>
10        <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
11      </providers>
12    </membership>

Let’s add a custom field to the User table by adding a Mobile property to the UserProfile entity (MVC4SimpleMembershipCodeFirstSeedingEF5/Models/AccountModel.cs).

1     [Table("UserProfile")]
2     public class UserProfile
3     {
4         [Key]
5         [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
6         public int UserId { get; set; }
7         public string UserName { get; set; }
8         public string Mobile { get; set; }
9     }

Enable EF5 CodeFirst Migrations

Seed your Roles and any Users you want to provision, also note the WebSecurity.InitializeDatabaseConnection method we are invoking. This method is what tells SimpleMembership which table to use when working with Users and which columns are for the UserId and UserName. I’m also going to demonstrate how you can hydrate additional custom columns such as requiring a User’s mobile number when registering on the site.

01    #region
02   
03    using System.Data.Entity.Migrations;
04    using System.Linq;
05    using System.Web.Security;
06    using MVC4SimpleMembershipCodeFirstSeedingEF5.Models;
07    using WebMatrix.WebData;
08   
09    #endregion
10   
11    namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations
12    {
13        internal sealed class Configuration : DbMigrationsConfiguration<UsersContext>
14        {
15            public Configuration()
16            {
17                AutomaticMigrationsEnabled = true;
18            }
19   
20            protected override void Seed(UsersContext context)
21            {
22                WebSecurity.InitializeDatabaseConnection(
23                    "DefaultConnection",
24                    "UserProfile",
25                    "UserId",
26                    "UserName", autoCreateTables: true);
27   
28                if (!Roles.RoleExists("Administrator"))
29                    Roles.CreateRole("Administrator");
30   
31                if (!WebSecurity.UserExists("lelong37"))
32                    WebSecurity.CreateUserAndAccount(
33                        "lelong37",
34                        "password",
35                        new {Mobile = "+19725000000"});
36   
37                if (!Roles.GetRolesForUser("lelong37").Contains("Administrator"))
38                    Roles.AddUsersToRoles(new[] {"lelong37"}, new[] {"Administrator"});
39            }
40        }
41    }

Now, run the update-database -verbose command from Package Manager Console, we are using the -verbose switch so that we can get better visibility on what’s getting executed on SQL. Notice the Mobile field is being created.

Let’s go ahead and do a sanity check and make sure all of our Users and Roles were provisioned correctly from the Seed method in our migration configuration, by executing a few queries.

01           SELECT TOP 1000 [UserId]
02                 ,[UserName]
03                 ,[Mobile]
04             FROM [aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5].[dbo].[UserProfile]
05             
06             SELECT TOP 1000 [RoleId]
07                 ,[RoleName]
08             FROM [aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5].[dbo].[webpages_Roles]
09             
10             SELECT TOP 1000 [UserId]
11                 ,[RoleId]
12             FROM [aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5].[dbo].[webpages_UsersInRoles]

Results



- Users were inserted
- Roles were provisioned
- The user “LeLong37″ was added and associated to the Administrator role

Finally for a sanity check, let’s go ahead and run the app and sign-in with the provisioned user from our Seed method.

One last thing, let’s go ahead and modify our Register view, Register model and AccountController to gather the user’s mobile number during registration.

Register View (Register.cshtml)

01           @model MVC4SimpleMembershipCodeFirstSeedingEF5.Models.RegisterModel
02           @{
03               ViewBag.Title = "Register";
04           }
05          
06           <hgroup class="title">
07               <h1>@ViewBag.Title.</h1>
08               <h2>Create a new account.</h2>
09           </hgroup>
10          
11           @using (Html.BeginForm()) {
12               @Html.AntiForgeryToken()
13               @Html.ValidationSummary()
14          
15               <fieldset>
16                   <legend>Registration Form</legend>
17                   <ol>
18                       <li>
19                           @Html.LabelFor(m => m.UserName)
20                           @Html.TextBoxFor(m => m.UserName)
21                       </li>
22                       <li>
23                           @Html.LabelFor(m => m.Password)
24                           @Html.PasswordFor(m => m.Password)
25                       </li>
26                       <li>
27                           @Html.LabelFor(m => m.ConfirmPassword)
28                           @Html.PasswordFor(m => m.ConfirmPassword)
29                       </li>
30                       <li>
31                           @Html.LabelFor(m => m.Mobile)
32                           @Html.TextBoxFor(m => m.Mobile)
33                       </li>
34                   </ol>
35                   <input type="submit" value="Register" />
36               </fieldset>
37           }
38          
39           @section Scripts {
40               @Scripts.Render("~/bundles/jqueryval")
41           }

Register model (AccountModel.cs)

01           public class RegisterModel
02           {
03               [Required]
04               [Display(Name = "User name")]
05               public string UserName { get; set; }
06          
07               [Required]
08               [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
09               [DataType(DataType.Password)]
10              [Display(Name = "Password")]
11               public string Password { get; set; }
12          
13               [DataType(DataType.Password)]
14               [Display(Name = "Confirm password")]
15               [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
16               public string ConfirmPassword { get; set; }
17          
18               [Required]
19               [DataType(DataType.PhoneNumber)]
20               [Display(Name = "Mobile")]
21               public string Mobile { get; set; }
22           }

Register Action (AccountController.cs)

01           [HttpPost]
02           [AllowAnonymous]
03           [ValidateAntiForgeryToken]
04           public ActionResult Register(RegisterModel model)
05           {
06               if (ModelState.IsValid)
07               {
08                   // Attempt to register the user
09                   try
10                   {
11                       WebSecurity.CreateUserAndAccount(
12                           model.UserName,
13                           model.Password,
14                           new { Mobile = model.Mobile },
15                           false);
16          
17                       WebSecurity.Login(model.UserName, model.Password);
18                       return RedirectToAction("Index", "Home");
19                   }
20                   catch (MembershipCreateUserException e)
21                   {
22                       ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
23                   }
24               }
25          
26               // If we got this far, something failed, redisplay form
27               return View(model);
28           }

Finally, let’s register.

Let’s go ahead and run our SQL queries again and make sure the mobile number was actually saved to our UserProfile table during the registration.

Sweet! Registration successful, with mobile number saved to the UserProfile table.

Happy Coding…!