entityframeworkのinclude実装
Dbモデル
public class Author
{
[Key]
public int AuthorId { get; set; }
public string Name { get; set; }
public List<Book> Books { get; set; }
}
public class Book
{
[Key]
public int BookId { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
DbContext
public class MyDbContext : DbContext
{
public DbSet<Book> Books { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Book>()
.HasOne(r => r.Author)
.WithMany(p => p.Books)
.HasForeignKey(r => r.AuthorId );
}
}
Contoller
var data= _context.Books.Include(r => r.Author).ToListAsync();