Reputation: 1
I have a problem when I'm trying to set the many-to-many relationship in EF Core, and catch the result in Swagger.
public class Book
{
[Key]
public int BookId { get; set; }
public string? BookName { get; set; }
}
public class Publisher
{
[Key]
public int PublisherId { get; set; }
public string? PublisherName { get; set; }
public ICollection<BookPublisher? BookPublishers { get; set; }
}
public class BookPublisher
{
[Key]
public int BookPublisherId { get; set; }
public int BookId { get; set; }
public int PublisherId { get; set; }
public Book? Book { get; set; }
}
In the DbContext
, I have:
DbSet<Publisher>? Publishers { get; set; }
DbSet<BookPublisher>? BookPublishers { get; set; }
DbSet<Book>? Books { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Publisher>().ToTable("TAB_Publisher", "dbo");
builder.Entity<BookPublisher>().ToTable("TAB_BookPublisher", "dbo");
builder.Entity<Book>().ToTable("TAB_Book", "dbo");
}
public List<Publisher>? GetPublishers()
{
if (Publishers != null)
return Publishers
.Include(s => s.BookPublishers).ThenInclude(s => s.Book)
.ToList<Publisher>();
else
return null;
}
When I call my method GetPublishers
in Swagger, I get exactly what I wanted:
[
{
"PublisherId": 1,
"PublisherName": "Publisher1",
"BookPublisher": [
{
"BookPublisherId": 1,
"BookId": 1,
"PublisherId": 1,
"Book": {
"BookId": 1,
"BookName": "TEST1",
}
},
{
"BookPublisherId": 2,
"BookId": 2,
"PublisherId": 1,
"Book": {
"BookId": 2,
"BookName": "TEST2",
}
},
]
}
]
How can I get the same result with the book? A book can have several publishers. What kind of relation do I have to set up?
Here is my cdm enter image description here
Upvotes: 0
Views: 57