我希望能够将n个用户与特定成就相关联。
public class VPTSDbContext : DbContext
{
public DbSet<Accomplishment> Accomplishments { get; set; }
public DbSet<User> Users { get; set; }
public VPTSDbContext(DbContextOptions options) : base(options) {}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserAccomplishment>().HasKey(ua => new { ua.AccomplishmentID, ua.UserID });
modelBuilder.Entity<UserAccomplishment>().HasOne(ua => ua.Accomplishment).WithMany(u => u.UserAccomplishments).HasForeignKey(ua => ua.AccomplishmentID);
modelBuilder.Entity<UserAccomplishment>().HasOne(ua => ua.User).WithMany(u => u.UserAccomplishments).HasForeignKey(ua => ua.UserID);
}
}
User.cs
public class User
{
[Required]
public string Name { get; set; }
[Key]
public int UserID { get; set; }
public virtual ICollection<UserAccomplishment> UserAccomplishments { get; set; }
}
Accomplishment.cs
public class Accomplishment
{
[Key]
public int AccomplishmentID { get; set; }
[Required]
public string Title { get; set; }
public virtual ICollection<UserAccomplishment> UserAccomplishments { get; set; }
}
这是我的链接表: 公共类UserAccomplishment {
[Required]
public int AccomplishmentID { get; set; }
public virtual Accomplishment Accomplishment { get; set; }
[Required]
public int UserID { get; set; }
public virtual User User { get; set; }
}
如何取回所有成就,包括用户模型?
我尝试了以下内容:
public List<Accomplishment> GetAll()
{
return dbContext.Accomplishments.Include(ua => ua.UserAccomplishments).ToList();
}
这将返回用户(在本例中为2,3和9),但我也需要用户的信息。
[{"accomplishmentID":1,"title":"Test Accomplishment","userAccomplishments":[{"accomplishmentID":1,"userID":2,"user":null},{"accomplishmentID":2,"userID":3,"user":null},{"accomplishmentID":2,"userID":9,"user":null}]}]
如何获取用户的信息?
仅供参考,用户在ThenInclude中不可用: