Asp Mvc如何为viewmodel分配加入的查询值?

问题描述 投票:1回答:1

我正在开发Asp.Net Mvc Web应用程序,我想为viewModel分配一个连接的linq查询值。

ViewModel:

public class BookDetails
{
    public int BookId { get; set; }

    [Display(Name = "Book Name :")]
    public string BookName { get; set; }

    [Display(Name = "BookDescription :")]
    public string BookDescription { get; set; }


    public int AuthorId { get; set; }

    public int BookGroupId { get; set; }

    [Display(Name = "Author Name :")]
    public string AuthorName { get; set; }

    [Display(Name = "Book Group Name :")]
    public string BookGroupName { get; set; }

}

我的视图在自身内部使用多模型,我创建了一个类来定义所有模型并在控制器中使用它:

多模型类:

public class MultiModels
{

    public List<ApplicationUser> UserListed { get; set; }

    public List<News> LastNews { get; set; }

    public List<BookDetails> bookdetails { get; set; }


}

最后在控制器中:

    public IActionResult BookDetails(int id)
    {
        if (id == 0)
        {
            return RedirectToAction("NotFounds");
        }

        MultiModels model = new MultiModels();

        model.UserListed = (from u in _userManager.Users orderby u.Id descending select u).Take(10).ToList();
        model.LastNews = (from n in _context.news orderby n.NewsId descending select n).Take(5).ToList();

////////////////////////////////////////Error location
        model.bookdetails = (from b in _context.books
                             join a in _context.authors on b.AuthorID equals a.AuthorId
                             join bg in _context.bookgroups on b.BookGroupID equals bg.BookGroupId
                             where b.BookId == id
                             select new
                             {
                                 b.BookId,
                                 b.BookDescription,
                                 b.BookName,
                                 b.AuthorID,
                                 b.BookGroupID,
                                 a.AuthorName,
                                 bg.BookGroupName
                             }).ToList();

        ////////////////////////////////////////

        return View(model);
    }

但在联接查询中,会发生以下错误:

Cannot implicitly convert type 'System.Collection.Generic.List<<anonymous type:int Bookid, string BookDescription, string BookName, int AuthorID, int BookGroupID, string AuthorName, string BookGroupName>>' to 'System.Collections.Generic.List<yourProject.Models.ViewModels.BookDetails>

c# jquery asp.net-mvc linq type-conversion
1个回答
4
投票
select new BookDetails
{
    BookId = b.BookId,
    BookDescription = b.BookDescription,
    BookName = b.BookName,
    AuthorId = b.AuthorID,
    BookGroupId = b.BookGroupID,
    AuthorName = a.AuthorName,
    BookGroupName = bg.BookGroupName
}).ToList();

将选择更改为上面的代码。当您的模型期望某种类型的List<BookDetails>时,您的选择是创建一个新的匿名类型。

© www.soinside.com 2019 - 2024. All rights reserved.