我延长了IdentityUser
和IdentityUserToken
。我正在尝试输出用户及其角色。我一直收到这个错误
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);
}
为什么UserId
或RoleId
不是导航属性,在这种情况下如何使用Include
?
答案 0 :(得分:0)
如果有人与扩展身份斗争,我会在此处发布答案,并且参考号为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。建设项目 - &gt;包管理器控制台 - &gt;运行add-migration addroletouser-&gt; Update-database
通过以下代码获取具有角色的用户:
var users = await _context.ApplicationUser.Include(u => u.Roles).ToListAsync();