3 Attachment(s)
Seed Roles and Users to an existing database in ASP.NET MVC 5 using Identity
Hello forum friends,
In this tutorial, I will demonstrate seeding roles and users to an existing database in an ASP.NET MVC 5 VB.NET application using Identity framework. For simplicity, I wil use a Northwind database or you may choose another database aside from this. This database doesn't have membership tables at all.
Attachment 141861
To begin with, accomplish the steps below:
1. Create an ASP.NET MVC project (VB) and then change web.config connectionStrings element to connect to an
existing database (Northwind as my example).
2. In Package Manager Console execute command
PM> Enable-Migrations
3. In Package Manager Console execute command
PM> Add-Migration ASPMembership
* This will create a file Timespan_ASPMembership.vb inside Migrations folder with scripts to create Membership
Tables such as AspNetUsers, AspNetRoles and etc..
4. In Package Manager Console execute command
PM> Update-Database
* This will add membership tables to Northwind database.
Attachment 141863
5. To seed Roles and Users, create a class SeedRolesAndUsers.vb inside Models folder. This class references
Microsoft.AspNet.Identity and Microsoft.AspNet.Identity.EntityFramework namespaces. The Seed() method
adds Customer or Manager role if they don't exist. The remaining part of the code creates a user and assign it
to a specific role.
VB.NET Code:
Public Class SeedRolesAndUsers
Public Shared Sub Seed(context As ApplicationDbContext)
Dim userManager = New UserManager(Of ApplicationUser)(New UserStore(Of ApplicationUser)(context))
Dim roleManager = New RoleManager(Of IdentityRole)(New RoleStore(Of IdentityRole)(context))
If Not roleManager.RoleExists("Customer") Then
Dim roleresult = roleManager.Create(New IdentityRole("Customer"))
End If
If Not roleManager.RoleExists("Manager") Then
Dim roleresult = roleManager.Create(New IdentityRole("Manager"))
End If
Dim userName As String = "jimmymgr01"
Dim password As String = "jimmymgr01"
Dim user As ApplicationUser = userManager.FindByName(userName)
If user Is Nothing Then
user = New ApplicationUser() With {
.UserName = userName
}
Dim userResult As IdentityResult = userManager.Create(user, password)
If userResult.Succeeded Then
Dim result = userManager.AddToRole(user.Id, "Manager")
End If
End If
End Sub
End Class
6. In Global.asax.vb Application_Start() method, call the seed method and then pass an ApplicationDBContext object to it.
VB.NET Code:
Dim context = New ApplicationDbContext()
SeedRolesAndUsers.Seed(context)
7. Run the application. You should see the tables AspNetRoles, AspNetUsers, AspNetUserRoles populated with data.
Attachment 141865
That's it.. :-)