samedi 10 mai 2014

using UserManager/IdentityFramework with an Int32 as TKey for IUser

This article is about how to use Int32 as a key for users in identity.

First the model. As I seed it, you can also see how to instanciate the UserManage.

For this thank you to SymbolSource and to Microsoft of course!

namespace cclw4c.Models
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit to learn more.
    public class ApplicationUser : IdentityUser <Int32, CustomUserLogin, CustomUserRole, CustomUserClaim&gt: {

    public class CustomRole : IdentityRole<Int32, CustomUserRole> {
        public CustomRole() { }
        public CustomRole(String name) { Name = name; }

    public class CustomUserRole : IdentityUserRole<Int32> { }
    public class CustomUserClaim : IdentityUserClaim<Int32> { }
    public class CustomUserLogin : IdentityUserLogin<Int32> { }

    public class ApplicationUserDbContext : IdentityDbContext<ApplicationUser, CustomRole, Int32, CustomUserLogin, CustomUserRole, CustomUserClaim>
        public ApplicationUserDbContext()
            : base("ApplicationUser")
            Database.SetInitializer<ApplicationUserDbContext>(new CreateDatabaseIfNotExistsWithSeedData());


    public class CreateDatabaseIfNotExistsWithSeedData : CreateDatabaseIfNotExists<ApplicationUserDbContext> {
        protected override void Seed(ApplicationUserDbContext context) {

            var user = new ApplicationUser() { UserName = "root" };
            UserManager<ApplicationUser, Int32> am = 
                new UserManager<ApplicationUser, Int32>(new UserStore<ApplicationUser, CustomRole, Int32, CustomUserLogin, CustomUserRole, CustomUserClaim>(context));
            IdentityResult ir = am.Create(user, "******");
            if (ir.Succeeded) {
                RoleManager<CustomRole, Int32> rm = new RoleManager<CustomRole, Int32>(new RoleStore<CustomRole, Int32, CustomUserRole>(context));
                rm.Create(new CustomRole("Root"));
                am.AddToRole(user.Id, "Root");
Second use
every where it is needed.
Hightlight on UserManager instanciation
new UserManager<ApplicationUser, Int32>(new UserStore<

Aucun commentaire:

Enregistrer un commentaire