gpt4 book ai didi

c# - Asp Mvc 如何将连接查询值分配给 viewmodel?

转载 作者:太空宇宙 更新时间:2023-11-03 20:58:45 27 4
gpt4 key购买 nike

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

View 模型:

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; }

}

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

多模型类:

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);
}

但是在连接查询中,出现了如下错误:

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>

最佳答案

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> 类型时,您的选择是创建一个新的匿名类型。 .

关于c# - Asp Mvc 如何将连接查询值分配给 viewmodel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47873822/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com