且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法在不指定 IdenitityUser、IdentityRole 和 IdentityDbContext 上的 TKey 的情况下创建自定义用户和角色?

更新时间:2021-08-30 22:18:26

看来答案是NO".如果您在 User 和/或 Role 上指定 TKey,则不再为您创建主键.

It appears the answer is "NO". If you specify the TKey on User and/or Role the primary keys are no longer created for you.

看来我是想把事情复杂化.感谢@dima 帮助我决定让事情变得简单.这是我为成功使用户和角色(均具有自定义属性)成功工作所做的工作,即通过控制器和视图在数据库中成功创建记录:

It seems I was trying to over-complicate things. Thanks @dima for helping me decide to un-complicate things. Here is what I did to successfully get users and roles (both with custom properties) to successfully work, i.e., to successfully create records in the database via a controller and view:

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

UPDATE: You may want to look at the link I provided at the bottom for a better/simpler solution.

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 of the model for the current context. 在这行代码 var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

However, a new issue has arose with the UserManager. Specifically, I'm getting the error The entity type IdentityRole is not part of the model for the current context. on this line of code var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

更新:在此处修复此错误:为什么我是否收到 IdentityRole 错误?

UPDATE: Fixed this error here: Why am I getting an IdentityRole error?