Get specific results from the database in .NET CORE

.net-core asp.net-core c# ef-core-2.0 entity-framework-core

Question

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.

enter image description here

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 enter image description here

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:

enter image description here

1
0
5/3/2018 4:57:15 AM

Popular Answer

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>
}
1
5/3/2018 10:25:05 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow