ASP.NET CORE 2 IdentityUser POCO错误

Nod*_*Dev 3 c# asp.net core asp.net-identity

我决定使用.NET Core 2,我遇到了问题.Microsoft文档说基类中不再存在导航属性IdentityUser,我希望它们能够恢复.

我可以参考每个用户在我的视图模型中的角色,但是当我将它放入我的应用程序用户类时:

public virtual ICollection<IdentityUserRole<int>> Roles { get; } = 
  new List<IdentityUserRole<int>>();
public virtual ICollection<IdentityUserClaim<int>> Claims { get; } = 
  new List<IdentityUserClaim<int>>();
public virtual ICollection<IdentityUserLogin<int>> Logins { get; } = 
  new List<IdentityUserLogin<int>>();
Run Code Online (Sandbox Code Playgroud)

并将其添加到我的模型构建器:

 builder.Entity<ApplicationUser>()
    .HasMany(e => e.Claims)
    .WithOne()
    .HasForeignKey(e => e.UserId)
    .IsRequired()
    .OnDelete(DeleteBehavior.Cascade);

builder.Entity<ApplicationUser>()
    .HasMany(e => e.Logins)
    .WithOne()
    .HasForeignKey(e => e.UserId)
    .IsRequired()
    .OnDelete(DeleteBehavior.Cascade);

builder.Entity<ApplicationUser>()
    .HasMany(e => e.Roles)
    .WithOne()
    .HasForeignKey(e => e.UserId)
    .IsRequired()
    .OnDelete(DeleteBehavior.Cascade);
Run Code Online (Sandbox Code Playgroud)

我收到了错误 The entity type 'IdentityUserLogin<int>' requires a primary key to be defined.

相关的Microsoft文档位于:https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

如何User.Role在视图中获取显示的值?

Man*_*nis 6

如果ApplicationUser类在不使用Generics定义主键类型的情况下扩展IdentityUser,则它使用默认类型(字符串).

在这种情况下,您必须将导航实体中的键类型从int更改为string.

您的ApplicationUser类应如下所示

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<IdentityUserRole<string>> Roles { get; } = new List<IdentityUserRole<string>>();
    public virtual ICollection<IdentityUserClaim<string>> Claims { get; } = new List<IdentityUserClaim<string>>();
    public virtual ICollection<IdentityUserLogin<string>> Logins { get; } = new List<IdentityUserLogin<string>>();
}
Run Code Online (Sandbox Code Playgroud)