【问题标题】:Can't get category's books even though the Book entity has a category foreign key?即使 Book 实体具有类别外键,也无法获取类别的书籍?
【发布时间】: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


    【解决方案1】:

    因为您要求第一个或默认值

    return _appDbContext.Categories.Include(category => category.books).FirstOrDefault(category => category.categoryId == categoryId);
    

    它返回它找到的第一个类别。这就是为什么你只有一个记录。它是一个关系数据库。每条记录都有一个 bookId 和一个 categoryId,它取第一个 where 为 true 的记录。

    如果您想要一个带有类别的书籍列表,您可以更改查询

    public IEnumerable<Book> getBooksByCategoryId(int categoryId)
            {
     return _appDbContext.Books.Include(c => c.category).Where(category => category.categoryId == categoryId).ToArray();
    }
    

    【讨论】:

    • 我没听懂你在说什么? '这就是为什么你只有一张唱片' ?不,我无法获得标题中所说的任何记录,我正在等待获得一个,因为只有一个,但没有工作!我得到'null'
    猜你喜欢
    • 2021-04-30
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多