MVC ASP 3表连接然后显示结果

时间:2015-09-23 10:18:15

标签: c# mysql asp.net asp.net-mvc linq

对于一个项目,我会显示添加到购物篮的书籍。我需要加入3个表来显示可用的格式:我这样做:BookID到bookID上的BookFormats,然后在formatID上将BookFormats格式化为格式。这是一个预先输出的数据库,我无法改变。我写了一个LINQ查询来显示它们并创建了一个具有所有3的属性的视图模型。

linq查询:

        IEnumerable<BookAndFormatViewModel> IEBooksRepository.GetAllBooksWithFormats()
    {
        var query =
            from book in eBooks.Books
            join format in eBooks.BookFormats on book.BookID equals format.BookID
            join formatName in eBooks.Formats on format.FormatID equals formatName.FormatID
            select new BookAndFormatViewModel();
        return query.ToList();

三者的视图模型:

    public int BookID { get; set; }
    public string ReferenceNumber { get; set; }
    public string Title { get; set; }
    public decimal Price { get; set; }
    public int FormatID { get; set; }
    public string FormatType { get; set; }

控制器代码:

        IEnumerable<BookModel> books = repository.GetAllBooks();
        IEnumerable<BookAndFormatViewModel> booksWithFormat = repository.GetAllBooksWithFormats();

        if (books.Count() == 0)
        {
            return PartialView("NoBooks");

        }
        return PartialView("Books", booksWithFormat);   

当我运行它时,它只显示空数据0和空字段。

1 个答案:

答案 0 :(得分:0)

最后的修复是更改模型的构造函数,然后像这样创建模型:

            var query =
            from book in eBooks.Books
            join format in eBooks.BookFormats on book.BookID equals format.BookID
            join formatName in eBooks.Formats on format.FormatID equals formatName.FormatID
            select new BookAndFormatViewModel
            {
                BookID = book.BookID,
                ReferenceNumber = book.ReferenceNumber,
                Title = book.Title,
                Price = book.Price,
                FormatID = format.FormatID,
                FormatType = formatName.FormatType
            };