有没有办法创建自定义用户和角色,而无需在IdenitityUser,IdentityRole和IdentityDbContext上指定TKey?

时间:2014-03-28 23:29:49

标签: asp.net asp.net-mvc entity-framework asp.net-mvc-5 asp.net-identity

有没有办法在stringIdentityUserIdentityRole中指定TKey IdentityDbContext而创建自定义用户和角色?我问,因为它似乎认为我不再需要自动生成的主键Id,我绝对会这样做。执行我在下面所做的工作,UserManager.Create(user, password)将因EntityValidationError上的Id而失败。

public class ApplicationUser : IdentityUser<string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    public string LastName { get; set; }
}

public class ApplicationUserLogin : IdentityUserLogin
{
}

public class ApplicationUserClaim : IdentityUserClaim
{
}

public class ApplicationUserRole : IdentityUserRole
{
}

public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    [Required]
    [StringLength(50)]
    public string ProperName { get; set; }

    [Required]
    public string Description { get; set; }
}


public class MyAppDb : IdentityDbContext<ApplicationUser, ApplicationRole, string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public MyAppDb()
        : base("MyAppDb")
    {
    }

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

2 个答案:

答案 0 :(得分:0)

我还在学习这个新的ASP.NET身份系统但是你试过省略这样的泛型类型:

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    public string LastName { get; set; }
}
{p>同样适用于ApplicationRole

MyAppDb看起来像这样:

public class MyAppDb: IdentityDbContext<ApplicationUser>

默认情况下,ID将是DB中自动生成的GUID的字符串

答案 1 :(得分:0)

似乎答案是“否”。如果您在User和/或Role上指定了TKey,则不再为您创建主键。

我似乎试图让事情过于复杂。感谢@dima帮助我决定让事情变得简单。以下是我成功获取用户和角色(包括自定义属性)以成功工作的方法,即通过控制器和视图在数据库中成功创建记录:

更新:您可能需要查看我在底部提供的链接,以获得更好/更简单的解决方案。

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    public string LastName { get; set; }
}

//public class ApplicationUserLogin : IdentityUserLogin
//{
//}

//public class ApplicationUserClaim : IdentityUserClaim
//{
//}

//public class ApplicationUserRole : IdentityUserRole
//{
//}

public class ApplicationRole : IdentityRole
{
    [Required]
    [StringLength(50)]
    public string ProperName { get; set; }
}


public class MyAppDb : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
    public MyAppDb()
        : base("MyAppDb")
    {
    }
}

然而,UserManager出现了一个新问题。具体来说,我在这行代码The entity type IdentityRole is not part of the model for the current context.

上收到错误var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

更新:修正了此错误:Why am I getting an IdentityRole error?