首页 文章

实体类型IdentityRole不是当前上下文Asp.net mvc的模型的一部分

提问于
浏览
0

我是MVC的新手 . 我正在创建角色管理器 . 截至目前,我已在web.config中添加了admin用户的凭据 .

我尝试通过添加所需的位置将数据类型字符串更改为整数并更新代码 . 截至目前,我认为在构建项目时没有错误 . 当我运行我的网站时,我得到上述错误 . Additional information: The entity type IdentityRole is not part of the model for the current context.

这是我的代码 .

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

我在这部分得到了错误 .

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

身份模型代码:

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

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代码:

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);
    }
}

启动验证码:

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);
    }
}

1 回答

  • 2

    当您实现自定义角色以将id从string转换为int时,您应该使用CustomRole来创建新角色

    //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);
    }
    

    像这样修改你的ApplicationRoleManager

    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>()));
        }
    }
    

相关问题