感谢您的帮助
两个班级:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public List<AuthorBook> Books { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public List<AuthorBook> Authors { get; set; }
}
public class AuthorBook
{
public int AuthorId { get; set; }
public Author Author { get; set; }
public int BookId { get; set; }
public Book Book { get; set; }
}
DataContext
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
// public DbSet<AuthorBook> AuthorBooks { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AuthorBook>()
.HasKey(t => new { t.AuthorId, t.BookId });
modelBuilder.Entity<AuthorBook>()
.HasOne(p => p.Author)
.WithMany(w => w.Books)
.HasForeignKey(h => h.AuthorId);
modelBuilder.Entity<AuthorBook>()
.HasOne(p => p.Book)
.WithMany(w => w.Authors)
.HasForeignKey(h => h.BookId);
}
}
控制器
[HttpGet]
public async Task<IActionResult> GetAuthors()
{
var authors = await this.context.Authors.Include(i => i.Books).ToListAsync();
return Ok(authors);
}
返回
{
"id": 1,
"name": "Paul",
"books": [
{
"authorId": 1,
"bookId": 2,
"book": null
},
{
"authorId": 1,
"bookId": 5,
"book": null
}
]
}
为什么authorId,bookId可以,但是不能直接访问对象书(为null)?
感谢您的帮助
答案 0 :(得分:2)
您要包含Books
导航属性,该属性是作者的AuthorBook
集合,而不是Book
。
public List<AuthorBook> Books { get; set; }
实际的Book
记录距离导航又一步了。要同时获得它们,您需要.ThenInclude()
:
var authors = await this.context.Authors
.Include(i => i.Books)
.ThenInclude(i => i.Book)
.ToListAsync();