ASP.NET Core 作者编辑页仅展示对应作者书籍的实现问题
问题解决:仅展示当前编辑作者名下的书籍
问题根源
当前代码里,AuthorEdit方法直接调用_bookService.GetAll()获取系统所有书籍,这是页面显示全部书籍的核心原因。另外GetByIdWithBooks方法未加载作者关联的Books集合,导致拿到的Author实体中Books属性为空。
修改方案
1. 修复GetByIdWithBooks方法(加载关联书籍)
Entity Framework默认不会自动加载导航属性,需显式用Include加载作者的书籍集合:
public Author GetByIdWithBooks(int authorId) { return BookContext.Authors .Include(a => a.Books) // 显式加载关联的Books集合 .Where(i => i.AuthorId == authorId) .FirstOrDefault(); }
2. 修改Admin Controller的AuthorEdit方法
将Books属性赋值为当前作者的书籍集合,替换原有的全量查询:
[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 = entity.Books, // 使用当前作者的书籍集合 AuthorId = entity.AuthorId, NameLastName = entity.NameLastName, Description = entity.Description, }; return View(model); }
备选方案:通过BookService按AuthorId查询
如果不想修改GetByIdWithBooks方法,可新增BookService查询方法实现:
第一步:在BookService中添加按AuthorId查询的方法
public List<Book> GetBooksByAuthorId(int authorId) { return BookContext.Books .Where(b => b.AuthorId == authorId) .ToList(); }
第二步:修改Controller中的赋值
var model = new AuthorModel() { Books = _bookService.GetBooksByAuthorId((int)id), // 按作者ID查询书籍 AuthorId = entity.AuthorId, NameLastName = entity.NameLastName, Description = entity.Description, };
验证要点
- 若未开启EF延迟加载,必须用
Include显式加载导航属性 - 确认
AuthorModel的Books属性类型与List<Book>匹配
内容的提问来源于stack exchange,提问作者Thor
相关产品推荐
相关产品推荐

