问题描述
我是asp.net的新手,所以我很容易:D,我正在构建一个简单的CRUD应用程序,我设法正确获取列表和路由,但是现在我想获取类别的书。
这就是我的书和类别实体:
public class Book
{
[Key]
public int bookId { get; set; }
public string bookName { get; set; }
public double bookPrice { get; set; }
public string bookImageUrl { get; set; }
[ForeignKey("Category")]
public int categoryId { get; set; }
public Category category { get; set; }
}
public class Category
{
[Key]
public int categoryId { get; set; }
public string categoryName { get; set; }
public string categoryDescription { get; set; }
public List<Book> books { get; set; }
}
public class CategoryRepository : ICategoryRepository
{
private readonly AppDbContext _appDbContext;
public CategoryRepository(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public IEnumerable<Category> getAllCategories()
{
return _appDbContext.Categories;
}
public Category getCategoryById(int categoryId)
{
return _appDbContext.Categories.Include(category => category.books).FirstOrDefault(category => category.categoryId == categoryId);
}
}
这是我的CategoryController,即使我不在这里也没问题:
private readonly ICategoryRepository _categoryRepository;
public CategoryController(ICategoryRepository categoryRepository)
{
_categoryRepository = categoryRepository;
}
public IActionResult categoryBooks(int idCategory)
{
Trace.WriteLine("this " + idCategory);
var booksListviewmodel = new BooksListviewmodel();
booksListviewmodel.Books = _categoryRepository.getCategoryById(idCategory).books;
return View(booksListviewmodel);
}
}
有什么想法吗?有指导吗?
任何帮助将不胜感激。
解决方法
由于您要输入第一个或默认值
return _appDbContext.Categories.Include(category => category.books).FirstOrDefault(category => category.categoryId == categoryId);
它返回找到的第一个类别。这就是为什么您只有一个记录的原因。它是一个关系数据库。每条记录都有一个bookId和一个categoryId,并在有真实记录的地方获得第一条记录。
如果您想要具有类别的清单图书,则可以对此进行更改查询
public IEnumerable<Book> getBooksByCategoryId(int categoryId)
{
return _appDbContext.Books.Include(c => c.category).Where(category => category.categoryId == categoryId).ToArray();
}