【问题标题】:ASP.NET CORE 2 IdentityUser POCO ErrorASP.NET CORE 2 IdentityUser POCO 错误
【发布时间】:2018-04-25 05:48:27
【问题描述】:

我决定使用 .NET Core 2,但遇到了问题。微软文档说导航属性不再存在于基类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>>();

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

 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);

我收到错误The entity type 'IdentityUserLogin&lt;int&gt;' requires a primary key to be defined.

相关的微软文档在这里:https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

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

【问题讨论】:

    标签: c# asp.net-core asp.net-identity


    【解决方案1】:

    如果您的 ApplicationUser 类扩展 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>>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多