【发布时间】:2018-06-01 02:41:40
【问题描述】:
我正在开发一个 Asp.Net Mvc Web 应用程序,我想将一个连接的 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; }
}
最后在 Controller 中:
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);
}
但是在joined查询中,出现如下错误:
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