I have two entities with many to many relationships in my .NET Core project:
Book:
public class Book
{
[Key]
public int BookId { get; set; }
public string Name { get; set; }
public string AuthorName { get; set; }
public int YearOfPublishing { get; set; }
public LibraryType Type { get; set; }
public virtual ICollection<BookPublicHouse> PublicHouses { get; set; }
public Book()
{
PublicHouses = new Collection<BookPublicHouse>();
}
}
Publicion House:
public class PublicHouse
{
[Key]
public int PublicHouseId { get; set; }
public string PublicHouseName { get; set; }
public string Country { get; set; }
public virtual ICollection<BookPublicHouse> Books { get; set; }
public PublicHouse()
{
Books = new Collection<BookPublicHouse>();
}
}
And I create join table:
public class BookPublicHouse
{
public virtual Book Book { get; set; }
public virtual PublicHouse PublicHouse { get; set; }
public int BookId { get; set; }
public int PublicHouseId { get; set; }
}
Here is context class:
public class LibraryContext : DbContext
{
public LibraryContext(DbContextOptions<LibraryContext> options)
: base(options)
{ }
public virtual DbSet<Book> Books { get; set; }
public virtual DbSet<PublicHouse> PublicHouses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookPublicHouse>()
.HasKey(bp => new { bp.BookId, bp.PublicHouseId });
}
}
So next I need to create Api's with CRUD operations, but I dont know how to create it. I dont know how to get book include all publicHouses, which this book contains
[Route("api/books")]
public class BookController : Controller
{
private LibraryContext _dbContext;
public BookController(LibraryContext context)
{
_dbContext = context;
this.mapper = mapper;
}
//get()
//get(id)
//create()
//update
//delete
}
For Entity Framework Core, one usually use Include()
followed by ThenInclude
To include "children of children" entities
var book = _dbContext.Books
.Include(b => b.PublicHouses)
.ThenInclude(bph => bph.PublicHouse)
.FirstOrDefault(b => b.BookId == 1);
(also, be aware that intellisense will trick you into believing this is not correct syntax, until you have written it completely, and sometimes you need to launch a successful build before it stops complaining)