【发布时间】:2021-02-13 03:22:47
【问题描述】:
我是 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);
}
}
我在数据库中有一本书和一个类别,仅此而已:
有什么想法吗?有指导吗?
任何帮助将不胜感激。
【问题讨论】:
标签: c# asp.net-mvc asp.net-core .net-core entity-framework-core