Home > Net >  Asp net core to list the author's books on the page
Asp net core to list the author's books on the page

Time:10-05

I want to show the books belonging to the author on the author edit page, but all the books are displayed on the page. I want to select and show only the books belonging to that author.

Admin Controller Page :

[HttpGet]
    public IActionResult AuthorEdit(int? id)
    {
        if(id==null)
        {
            return NotFound();
        }
        var entity = _authorService.GetByIdWithBooks((int)id);

        if(entity==null)
        {
            return NotFound();

        }
        var model = new AuthorModel()
        {
            Books = _bookService.GetAll(),
            AuthorId = entity.AuthorId,
            NameLastName = entity.NameLastName,
            Description = entity.Description,

        };
        return View(model);
    }

GetByIdWithBooks

public Author GetByIdWithBooks(int authorId)
    {
        return BookContext.Authors
                    .Where(i=>i.AuthorId==authorId)
                    .FirstOrDefault();
    }

Book Model :

public class Book
{
    public int BookId { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
    public double? Price { get; set; } 
    public string Description { get; set; } 
    public string ImageUrl { get; set; }
    public string BarcodeNumber { get; set; }
    public int PageCount { get; set; }
    public string FirstPrintDate { get; set; }
    public bool IsApproved { get; set; }
    public bool IsHome { get; set; }
    public DateTime DateAdded { get; set; }
    public List<BookCategory> BookCategories { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
    public int PublisherId { get; set; }
    public Publisher Publisher { get; set; }

}

Author Model :

public class Author
{
    public int AuthorId { get; set; }
    public string NameLastName { get; set; }
    public string ImageUrl { get; set; }
    public string Description { get; set; }
    public List<Book> Books { get; set; }

}

CodePudding user response:

If you're using EF you could just change GetByIdWithBooks() method to do it, and it would make sense.

public Author GetByIdWithBooks(int authorId)
{
    return BookContext.Authors
                .Include(c => c.Books)
                .Where(i=>i.AuthorId==authorId)
                .FirstOrDefault();
}

Since you have a FK between Books -> Author the "Include" would make the necessary joins to bring back the related books.

Or, if you want to keep the _booksService.GetAll() call, which in my opinion, may not make a lot of sense:

_bookService.GetAll().Where(c => c.AuthorId == id)

Which should probably be a different method inside your service.

Is that what you were trying to achieve?

  • Related