种子自定义角色从IdentityRole继承

时间:2015-07-25 20:50:42

标签: asp.net-mvc inheritance asp.net-mvc-5 entity-framework-6 ef-migrations

这次问题是当我尝试构建一个继承IdentityRole的类时,就像这样

public class Role : IdentityRole, IObjectState
{
    public Role() { }
    public Role(string name) : base(name) { Name = name; }
    public new string Name { get; set; }
    [NotMapped]
    public ObjectState ObjectState { get; set; }
    public virtual List<UserPermission> UserPermissions { get; set; }
}

然后我想用我的角色为我的数据库播种,但是它的Discriminator Column我希望它的值为'Role'而不是'IdentityRole'

这是我的播种代码

if (!context.Roles.Any(r => r.Name == "Administrator") || !context.Roles.Any(r => r.Name == "User"))
        {
            var store = new RoleStore<IdentityRole>(context);
            var manager = new RoleManager<IdentityRole>(store);
            var role = new List<IdentityRole>()
            {
                new IdentityRole { Name = "Administrator"},
                new IdentityRole { Name = "User"},
            };
            role.ForEach(x => manager.Create(x));
        }

当我尝试这个种子代码时它没关系,在它的Discriminator Column中它显示'IdentityRole'但是当我尝试这个时,它没有将角色保存在表中

if (!context.Roles.Any(r => r.Name == "qwe") || !context.Roles.Any(r => r.Name == "qweqwe"))
        {
            var store = new RoleStore<Role>(context);
            var manager = new RoleManager<Role>(store);
            List<Role> role = new List<Role>()
            {
                new Role() { Name = "qwe"},
                new Role() { Name = "qweqwe"},
            };
            role.ForEach(x => manager.Create(x));
        }

我不知道为什么这段代码无法保存角色,因为你可以看到我应该保存它,因为Role Class继承自IdentityRole

我应该怎样做才能让我的角色与不同的判别者一起播种?

先谢谢

1 个答案:

答案 0 :(得分:0)

好的,我的解决方案非常简单lol

我改变了这个

if (!context.Roles.Any(r => r.Name == "qwe") || !context.Roles.Any(r => r.Name == "qweqwe"))
    {
        var store = new RoleStore<Role>(context);
        var manager = new RoleManager<Role>(store);
        List<Role> role = new List<Role>()
        {
            new Role() { Name = "qwe"},
            new Role() { Name = "qweqwe"},
        };
        role.ForEach(x => manager.Create(x));
    }

这个

if (!context.Roles.Any(r => r.Name == "Administrator") || !context.Roles.Any(r => r.Name == "User"))
        {
            var role = new List<Role>()
            {
                new Role { Name = "Administrator"},
                new Role { Name = "User"},
            };
            role.ForEach(x => context.Roles.Add(x));
        }

那就是它 我意识到你可以使用你的上下文为你的表做种子,而不用你的ApplicationRole或UserManager