I am trying to display random books on the homepage of my project. Every book has one or many authors, but when I iterate it shows all authors (currently in the database) on the homepage. Could you help me figure it out. I want to show the correct authors per book.
When I am having an ID in the route it is easy and it works, but I don't know what to link to now that I don't have any ID in the homepage.
Here is a correct individual result
for which I've used a simple EF core code
var book = await _appDbContext.Books
.Include(b => b.BookAuthors)
.ThenInclude(a => a.Author)
.AsNoTracking()
.SingleOrDefaultAsync(m => m.BookId == id);
NOW for the problem:
I am using a ViewComponent which I then inject into my Home page
@foreach (var item in Model.BookAuthors)
{
<span><a asp-controller="Author" asp-action="Details" asp-route-id="@item.AuthorId">@item.Author.Name</a></span>
}
But, like I've said, now it iterates over all of the authors in my database and does not connect to specific books.
Here is my BookslistViewComponent.cs
public class BooksListViewComponent : ViewComponent
{
private readonly ApplicationDbContext _appDbContext;
public BooksListViewComponent(ApplicationDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var randomBooksList = await GetRandomBooksAsync(3);
return View(randomBooksList);
}
private Task<List<Book>> GetRandomBooksAsync(int numBooks)
{
return _appDbContext.Books.OrderBy(r => Guid.NewGuid()).Take(numBooks)
.Include(b => b.BookAuthors)
.ThenInclude(a => a.Author)
.ToListAsync();
}
}
Here is my database:
I think your Home Page should change :
@foreach (var item in Model.BookAuthors)
{
<span><a asp-controller="Author" asp-action="Details" asp-route-
id="@item.AuthorId">@item.Name</a></span>
}