Database model:
Create table Author
(
AuthorID int primary key identity,
Name nvarchar(50)
)
Create table Book
(
BookID int primary key identity,
Name nvarchar(50),
PageCount int
)
Create table AuthorBook
(
AuthorID int not null foreign key references Author(AuthorID),
BookID int not null foreign key references Book(BookID)
)
OnModel Creating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Author> Author { get; set; }
public virtual DbSet<AuthorBook> AuthorBook { get; set; }
public virtual DbSet<Book> Book { get; set; }
public virtual DbSet<BookGenre> BookGenre { get; set; }
public virtual DbSet<Genre> Genre { get; set; }
public virtual DbSet<MyBook> MyBook { get; set; }
public virtual DbSet<Person> Person { get; set; }
}
There are many to many relationship in book and author tables with the autor_book
junction table. How do I get books with the authors?
using (MyLibraryEntities db = new MyLibraryEntities())
{
var query = db.Book.SelectMany(book => db.Author, (book, author) =>
new {
bookID = book.BookID,
name = book.Name,
pageCount = book.PageCount,
authorId = author.AuthorID,
authorName = author.Name
}).ToList<dynamic>();
}
I expect to get the list like
books = [{"name": book name, "pageCount": 233, authors = {"Carl", "Mike"}, ....].
But the actual output is;
[{"name": book name", .. author: "Carl"}, {"name": book, ... author: "Mike"]