我扩展了我的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
?
万一有人与扩展身份斗争我在这里发布答案,而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
var users = await _context.ApplicationUser.Include(u => u.Roles).ToListAsync();