扩展ASP.NET身份角色:IdentityRole不是为当前上下文模型的一部分 [英] Extending ASP.NET Identity Roles: IdentityRole is not part of the model for the current context

查看:709
本文介绍了扩展ASP.NET身份角色:IdentityRole不是为当前上下文模型的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用新的ASP.NET身份在我MVC5的应用程序,特别是我想ASP.NET身份集成到现有的数据库。我已经阅读SO有关DB第一和ASP.NET身份问题/答案,已经遵循所有的建议,我还是不能角色添加到我的数据库,但我没有问题添加用户。这里是我的code:

I'm trying to use the new ASP.NET Identity in my MVC5 application, specifically I'm trying to integrate ASP.NET Identity into an existing database. I've already read the questions/answers on SO pertaining to DB First and ASP.NET Identity, and having followed all the recommendations I still can't add roles to my database, although I have no problems adding users. Here's my code:

var context = new PayrollDBEntities();
var roleManager = new RoleManager<AspNetRole>(new RoleStore<AspNetRole>(context));

bool roleExists = roleManager.RoleExists(roleDto.Name);
if (roleExists){
    return false;
}

var role = new AspNetRole(roleDto.Name){
    Name = roleDto.Name,
};

IdentityResult result = roleManager.Create(role);//Getting exception here

在code的最后一行我得到类型的异常'System.InvalidOperationException':实体类型IdentityRole是不是模型当前上下文的一部分

下面是我的背景:

public partial class PayrollDBEntities : IdentityDbContext
{
        public PayrollDBEntities()
            : base("name=PayrollDBEntities")
        {
        }

        public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
        public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
        public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
        public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
......
}

我的 AspNetUser AspNetRole 类从 IdentityUser 派生分别 IdentityRole ,但我仍然收到这个例外。这里是我的数据库图:

My AspNetUser and AspNetRole classes derive from IdentityUser and IdentityRole respectively, but I'm still getting that exception. Here is my database diagram:

任何帮助将大大AP preciated。

Any help would be greatly appreciated.

推荐答案

在试图让这一个干净的方式工作了几天,我得出的结论,如果你先用数据库和希望到ASP.NET身份融入您的应用程序,目前最简单,最干净的解决方案是通过覆盖ASP.NET身份来创建自己的成员提供。它实际上是pretty容易的,到目前为止,我已经实现了 UserStore Rolestore的我的胃口。我已经添加了特定于我的域名列/关系在我的数据库,每当我创建了一个用户或角色,我照顾我的数据库中承诺在加入所需关系。我的 UserStore 的实施颇为相似,<一个href=\"http://weblogs.asp.net/imranbaloch/archive/2013/12/12/a-simple-implementation-of-microsoft-aspnet-identity.aspx\"相对=nofollow>这个。我的 Rolestore的的实施是这样的:

After a few days of trying to get this to work in a clean manner, I've come to the conclusion that if you're using Database first and want to integrate ASP.NET Identity into your app, by far the easiest and cleanest solution is to create your own membership provider by overriding ASP.NET Identity. It's actually pretty easy, so far I've implemented UserStore and RoleStore to my liking. I've added columns/relations specific to my domain in my database, and whenever I create a user or a role, I take care of my database commits by adding the required relations. My UserStore implementation is quite similar to this. My RoleStore implementation is something like this:

public class ApplicationRoleStore : IRoleStore<ApplicationRoleDTO>
{
    private PayrollDBEntities _context;
    public ApplicationRoleStore() { }

    public ApplicationRoleStore(PayrollDBEntities database)
    {
        _context = database;
    }

    public Task CreateAsync(ApplicationRoleDTO role)
    {
        if (role == null)
        {
            throw new ArgumentNullException("RoleIsRequired");
        }
        var roleEntity = ConvertApplicationRoleDTOToAspNetRole(role);
        _context.AspNetRoles.Add(roleEntity);
        return _context.SaveChangesAsync();

    }

    public Task DeleteAsync(ApplicationRoleDTO role)
    {
        var roleEntity = _context.AspNetRoles.FirstOrDefault(x => x.Id == role.Id);
        if (roleEntity == null) throw new InvalidOperationException("No such role exists!");
        _context.AspNetRoles.Remove(roleEntity);
        return _context.SaveChangesAsync();
    }

    public Task<ApplicationRoleDTO> FindByIdAsync(string roleId)
    {
        var role = _context.AspNetRoles.FirstOrDefault(x => x.Id == roleId);

        var result = role == null
            ? null
            : ConvertAspNetRoleToApplicationRoleDTO(role);

        return Task.FromResult(result);
    }

    public Task<ApplicationRoleDTO> FindByNameAsync(string roleName)
    {

        var role = _context.AspNetRoles.FirstOrDefault(x => x.Name == roleName);

        var result = role == null
            ? null
            : ConvertAspNetRoleToApplicationRoleDTO(role);

        return Task.FromResult(result);
    }

    public Task UpdateAsync(ApplicationRoleDTO role)
    {

        return _context.SaveChangesAsync();
    }

    public void Dispose()
    {
        _context.Dispose();
    }
    private ApplicationRoleDTO ConvertAspNetRoleToApplicationRoleDTO(AspNetRole aspRole)
    {
        return new ApplicationRoleDTO{
            Id = aspRole.Id,
            EnterpriseId = aspRole.EnterpriseId,
            Name = aspRole.Name
        };
    }

    private AspNetRole ConvertApplicationRoleDTOToAspNetRole(ApplicationRoleDTO appRole)
    {
        return new AspNetRole{
            Id = appRole.Id,
            EnterpriseId = appRole.EnterpriseId,
            Name = appRole.Name,
        };
    }
}

和我ApplicationRoleDTO:

And my ApplicationRoleDTO:

public class ApplicationRoleDTO : IRole
{
    public ApplicationRoleDTO()
    {
        Id = Guid.NewGuid().ToString();
    }

    public ApplicationRoleDTO(string roleName)
        : this()
    {
        Name = roleName;
    }
    public string Id { get; set; }
    public string Name { get; set; }
    public Guid EnterpriseId { get; set; }
}

我还发现这2篇文章pretty有所帮助:

I also found these 2 articles pretty helpful:

<一个href=\"http://www.asp.net/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity\"相对=nofollow>自定义存储提供程序ASP.NET身份概述

<一个href=\"http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider\"相对=nofollow>实现自定义的MySQL ASP.NET身份存储提供商

这篇关于扩展ASP.NET身份角色:IdentityRole不是为当前上下文模型的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆