user7090664
user7090664

Reputation: 45

The entity type IdentityRole is not part of the model for the current context Asp.net mvc

I am new to MVC. I am working on creating role manager. As of now, I have added credentials for admin user in web.config.

I tried to change datatype string to integer and updated code by adding in required places. As of now I see no error while building project. When I run my website, i get above mentioned error. Additional information: The entity type IdentityRole is not part of the model for the current context.

Here is my code.

private void CreateAdminIfNeeded()
    {
        // Get Admin Account
        string AdminUserName = ConfigurationManager.AppSettings["AdminUserName"];
        string AdminPassword = ConfigurationManager.AppSettings["AdminPassword"];
        string fileName = HttpContext.Server.MapPath(@"~/Images/noImg.png");

        byte[] imageData = null;
        FileInfo fileInfo = new FileInfo(fileName);
        long imageFileLength = fileInfo.Length;
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        imageData = br.ReadBytes((int)imageFileLength); 
        // See if Admin exists
        var objAdminUser = UserManager.FindByEmail(AdminUserName);

        if (objAdminUser == null)
        {
            //See if the Admin role exists. In this part I am getting error
            if (!RoleManager.RoleExists("Administrator"))
            {
                // Create the Admin Role (if needed)
                IdentityRole objAdminRole = new IdentityRole("Administrator");
                RoleManager.Create(objAdminRole);
            }

            // Create Admin user
            var objNewAdminUser = new ApplicationUser { UserName = AdminUserName, Email = AdminUserName, UserPhoto = imageData };
            var AdminUserCreateResult = UserManager.Create(objNewAdminUser, AdminPassword);
            // Put user in Admin role
            UserManager.AddToRole(objNewAdminUser.Id, "Administrator");
        }
    }
    #endregion

I am getting error here in this part.

//See if the Admin role exists. 
            if (!RoleManager.RoleExists("Administrator"))
            {
                // Create the Admin Role (if needed)
                IdentityRole objAdminRole = new

Identity Model code:

namespace SoftechGoSMS.Models { public class ApplicationUser : IdentityUser { public byte[] UserPhoto { get; set; }

    public string DomainName { get; set; }
    public string CompanyName { get; set; }
    public string CopyrightInformation { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

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

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

public class CustomUserStore : UserStore<ApplicationUser, CustomRole, int,
    CustomUserLogin, CustomUserRole, CustomUserClaim>
{
    public CustomUserStore(ApplicationDbContext context)
        : base(context)
    {
    }
}

public class CustomRoleStore : RoleStore<CustomRole, int, CustomUserRole>
{
    public CustomRoleStore(ApplicationDbContext context)
        : base(context)
    {
    }
} 

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, 
int, CustomUserLogin, CustomUserRole, CustomUserClaim>  
{
    public ApplicationDbContext()
        : base("SMSGoConnection")
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

}

    #region public ApplicationRoleManager RoleManager
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ??
                HttpContext.GetOwinContext()
                .GetUserManager<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

Application Role Manager code:

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
        : base(store)
    {
    }
    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
        return new ApplicationRoleManager(roleStore);
    }
}

Startup Auth code:

 public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Add Role Manager
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);


        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                getUserIdCallback: id => id.GetUserId<int>())
            }
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
    }
}

Upvotes: 0

Views: 1021

Answers (1)

Umair Anwaar
Umair Anwaar

Reputation: 1136

When you implement custom role to make id from string to int so you should use CustomRole to create new role

//See if the Admin role exists. In this part I am getting error
if (!RoleManager.RoleExists("Administrator"))
{
    // Create the Admin Role Using CustomRole not IdenitityRole
    CustomRole objAdminRole = new CustomRole("Administrator");
    RoleManager.Create(objAdminRole);
}

Modify your ApplicationRoleManager like this

public class ApplicationRoleManager : RoleManager<CustomRole, int>
{
    public ApplicationRoleManager(IRoleStore<CustomRole, int> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new CustomRoleStore(context.Get<ApplicationDbContext>()));
    }
}

Upvotes: 2

Related Questions