多对多关系返回对象null但正确的id

时间:2018-10-30 15:08:50

标签: entity-framework-core

感谢您的帮助

两个班级:

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)?

感谢您的帮助

1 个答案:

答案 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();