วันจันทร์ที่ 28 พฤศจิกายน พ.ศ. 2559

Example of Create the roles and the users using ASP.NET Identity

Protected Overrides Sub Seed(context As ApplicationDbContext)
    Dim store As New RoleStore(Of IdentityRole)(context)
    Dim Rolemanager As New RoleManager(Of IdentityRole)(store)
 
    If Not context.Roles.Any(Function(r) r.Name = "Manager"Then
        Dim role As New IdentityRole With {.Name = "Manager"}
        Rolemanager.Create(role)
    End If
    If Not context.Roles.Any(Function(r) r.Name = "Admin"Then
        Dim role As New IdentityRole With {.Name = "Admin"}
        Rolemanager.Create(role)
    End If
 
 
    Dim userStore As New UserStore(Of ApplicationUser)(context)
    Dim Usermanager As New UserManager(Of ApplicationUser)(userStore)
    If Not context.Users.Any(Function(u) u.UserName = "admin@management.com"Then
        Dim user As New ApplicationUser With {.UserName = "admin@management.com",
           .Email = "admin@management.com"}
        Usermanager.Create(user, "Admin123!!")
        Usermanager.AddToRole(user.Id, "Admin")
        Usermanager.AddToRole(user.Id, "Manager")
 
 
        End If
 
    MyBase.Seed(context)
 
End Sub


The context object is the database context, you can create anywhere in the page.

Dim mycontext As New ApplicationDbContext

In the example, the code creates Manager and Admin roles if it does not exist in the database.
Then, it creates an admin user admin@management.com. The user is assigned to both Admin and Manager roles.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น