Linq 使用include.select进行EF代码首次查询疯狂
我和林克大吵了一架 我有一个网页和一个zonecontent实体 在我的网页存储库中,我有一个名为GetPageByTitle的方法 在这里,我想按标题选择页面并返回它。 我试着这样做:Linq 使用include.select进行EF代码首次查询疯狂,linq,frameworks,lambda,entity,code-first,Linq,Frameworks,Lambda,Entity,Code First,我和林克大吵了一架 我有一个网页和一个zonecontent实体 在我的网页存储库中,我有一个名为GetPageByTitle的方法 在这里,我想按标题选择页面并返回它。 我试着这样做: public WebPage GetPageByTitle(string title,string cultureName) { try { var entity = (from p in GetAll().Inc
public WebPage GetPageByTitle(string title,string cultureName)
{
try
{
var entity =
(from p in GetAll().Include(x => x.Site).Include(x => x.Menu)
from c in p.ZoneContents
where c.Language.CultureName == cultureName && c.PageTitle == title
select new
{
page = p,
zone = c
}).SingleOrDefault();
}
catch (InvalidOperationException)
{
throw new ArgumentException("There are no visiblepages with the provided title and language");
}
catch (Exception ex)
{
throw new ArgumentException(ex.Message);
}
}
现在我有一个类型{Webpage,ZoneContent},无法返回到Webpage中
如何进一步将它们组合到网页中
有人有主意吗
非常感谢您可以这样尝试: 如果您只想要该网页,则不需要投影到匿名类型。只需选择p 如果没有结果,你不会得到异常。SingleOrDefault将返回实体或null。因此,只需在查询后测试null 不要捕获泛型异常。如果此查询引发意外异常,请让应用程序崩溃并修复错误
当您进行联接时,Include语句被忽略。@Eranga:是的,谢谢!我试过一个新版本。我不知道如果没有扩展方法和lambda,我是否可以表达这一点。
public WebPage GetPageByTitle(string title,string cultureName)
{
var webPage =
(from p in GetAll().Include(x => x.Site).Include(x => x.Menu)
where p.ZoneContents.Any(c => c.Language.CultureName == cultureName
&& c.PageTitle == title)
select p)
.SingleOrDefault();
if (webPage == null)
throw new ArgumentException(
"There are no visiblepages with the provided title and language");
return webPage;
}