我需要从我的存储库返回我的viewmodel类的单个实例,以便将其提供给强类型视图
在我的存储库中,这适用于viewmodel实例的集合:
IEnumerable<PAWeb.Domain.Entities.Section> ISectionsRepository.GetSectionsByArea(int AreaId)
{
var _sections = from s in DataContext.Sections where s.AreaId == AreaId orderby s.Ordinal ascending select s;
return _sections.Select(x => new PAWeb.Domain.Entities.Section()
{
SectionId = x.SectionId,
Title = x.Title,
UrlTitle = x.UrlTitle,
NavTitle = x.NavTitle,
AreaId = x.AreaId,
Ordinal = x.Ordinal
}
);
}
但是当我试图获得一个单一的实体时,就像这样:
public PAWeb.Domain.Entities.Section GetSection(int SectionId)
{
var _section = from s in DataContext.Sections where s.SectionId == SectionId select s;
return _section.Select(x => new PAWeb.Domain.Entities.Section()
{
SectionId = x.SectionId,
Title = x.Title,
UrlTitle = x.UrlTitle,
NavTitle = x.NavTitle,
AreaId = x.AreaId,
Ordinal = x.Ordinal
}
);
}
我得到了
Error 1 Cannot implicitly convert type
'System.Linq.IQueryable<PAWeb.Domain.Entities.Section>' to
'PAWeb.Domain.Entities.Section'. An explicit conversion exists
(are you missing a cast?)"
这一定很简单,但我是c#的新手,我无法弄清楚这个演员。我在各个地方尝试过(PAWeb.Domain.Entities.Section)但没有成功。任何人都可以帮忙??
答案 0 :(得分:2)
您的查询返回IQueryable,可能有多个项目。例如,考虑数组或对象列表与单个对象之间的区别。它不知道如何将List转换为单个对象,应该采用哪一个?首先?最后一次?
你需要具体告诉它只带一件物品。
e.g。
public PAWeb.Domain.Entities.Section GetSection(int SectionId)
{
var _section = from s in DataContext.Sections where s.SectionId == SectionId select s;
return _section.Select(x => new PAWeb.Domain.Entities.Section()
{
SectionId = x.SectionId,
Title = x.Title,
UrlTitle = x.UrlTitle,
NavTitle = x.NavTitle,
AreaId = x.AreaId,
Ordinal = x.Ordinal
}
).FirstOrDefault();
}
这将返回第一个项目,如果没有与您的查询匹配的项目,则返回null。在你的情况下,除非表是空的,否则不会发生,因为你没有where子句。