为什么EF一直拒绝在IdentityUserRole中的扩展主键上“包含”?

问题描述 投票:0回答:1

我扩展了我的IdentityUserIdentityUserToken。我正在尝试输出用户及其角色。我一直收到这个错误

InvalidOperationException:属性“RoleId”不是实体类型“IdentityUserRole”的导航属性。 'Include(string)'方法只能与'。'一起使用。分隔的导航属性名称列表。

    [HttpGet]
    public async Task<IActionResult> GetUsersList()
    {
      var users = await context.UserRoles
                        .Include(x=>x.RoleId)
                        .ToListAsync();

        return Ok(users);

    }

所以我试图添加我的DbContext也不起作用,

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

         modelBuilder.Entity<IdentityUserRole<string>>().HasKey(hk => new { hk.UserId, hk.RoleId});
          base.OnModelCreating(modelBuilder);
    }

为什么UserIdRoleId不是导航属性,在这种情况下如何使用Include

c# entity-framework asp.net-identity
1个回答
0
投票

万一有人与扩展身份斗争我在这里发布答案,而ref是here

1.修改ApplicationUser以添加角色属性

// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
    /// <summary>
    /// Navigation property for the roles this user belongs to.
    /// </summary>
    public virtual ICollection<IdentityUserRole<string>> Roles { get; } = new List<IdentityUserRole<string>>();

    // your rest properties
}

2.修改ApplicationDbContext以将角色添加到用户实体

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    public DbSet<ApplicationUser> ApplicationUser { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
        builder.Entity<ApplicationUser>()
                .HasMany(e => e.Roles)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);
    }
}

3.构建项目 - >包管理器控制台 - >运行add-migration addroletouser-> Update-database

  1. 通过以下代码获取具有角色的用户: var users = await _context.ApplicationUser.Include(u => u.Roles).ToListAsync();
© www.soinside.com 2019 - 2024. All rights reserved.