我正在尝试从LINQ to Entities查询填充ViewModel
,但我收到错误
无法将类型'System.Linq.IQueryable隐式转换为GameSEctionVM
我不确定我应该使用什么转换。我在网上看到很多虚拟机拥有多个版本的数据(比如一个查询结果列表),但没有一个代表像这样的单行数据。我做错了什么?
using (SectionContext db = new SectionContext())
{
string RouteName = RouteData.Values["RouteName"].ToString();
GameSectionVM model = (from s in db.Sections
join f in db.Files on s.LogoFileID equals f.ID
where s.RouteName == RouteName
select new GameSectionVM
{
GameTitle = s.Title,
LogoFileName = f.FileName,
Synopsis = s.Synopsis
});
return View(model);
}
public class GameSectionVM
{
public string GameTitle { get; set; }
public string LogoFileName { get; set; }
public string Synopsis { get; set; }
}
答案 0 :(得分:2)
只需添加.FirstOrDefault()
GameSectionVM model = (from s in db.Sections
join f in db.Files on s.LogoFileID equals f.ID
where s.RouteName == RouteName
select new GameSectionVM
{
GameTitle = s.Title,
LogoFileName = f.FileName,
Synopsis = s.Synopsis
}).FirstOrDefault();
这会将类型为System.Linq.IQueryable
的linq转换为单个GameSectionVM
对象。
答案 1 :(得分:0)
您的L2S查询未返回GameSectionVM对象。它返回一个未执行的查询,因此IQueryable。实际上是一个或多个对象,您需要执行查询。为此,您可以调用ToArray,ToList,First,Single,FirstOrDefault,SingleOrDefault,Count等方法,或者使用foreach
循环枚举结果。在您的情况下,您似乎期待单个对象,因此Single或SingleOrDefault是合适的。如果总有一个对象,则使用Single但如果可能没有匹配则使用SingleOrDefault并测试null
。