我想在作者編輯頁面上顯示屬于作者的書籍,但所有書籍都顯示在頁面上。我只想選擇并顯示屬于該作者的書籍。
管理員控制器頁面:
[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();
}
圖書型號:
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; }
}
作者型號:
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; }
}
uj5u.com熱心網友回復:
如果您使用的是 EF,您只需更改GetByIdWithBooks()方法即可,這將是有意義的。
public Author GetByIdWithBooks(int authorId)
{
return BookContext.Authors
.Include(c => c.Books)
.Where(i=>i.AuthorId==authorId)
.FirstOrDefault();
}
由于您在 Books -> Author 之間有一個 FK,因此“包含”將進行必要的連接以帶回相關書籍。
或者,如果您想保留 _booksService.GetAll() 呼叫,在我看來,這可能沒有多大意義:
_bookService.GetAll().Where(c => c.AuthorId == id)
這可能應該是您服務中的不同方法。
這就是你想要達到的目標嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511754.html
上一篇:ASP.NET核心MVC RazorPOST控制器回傳“錯誤請求”
下一篇:ASP.NETCoreWebAPI-System.InvalidOperationException:LINQ運算式'DbSet<Mandate>()
