我对LINQ和实体framwework还不太熟悉。
我必须从数据库获取站点地图并将其写入XML。
主要问题是,在以下代码中,子查询根本没有显示任何内容:
var pages = (from p in ctx.CMSPages2
where p.MenuID == num && p.ParentID == 0
select new
{
URLLevel1 = p.KeywordUrl + "/" + p.FriendlyUrl,
TitleLevel1 = p.LinkTitle,
Level2 = from q in ctx.CMSPages2
where q.ParentID == p.SitemapExternID
select new
{
URLLevel2 = q.KeywordUrl + "/" + q.FriendlyUrl,
TitleLevel2 = q.LinkTitle,
}
}).ToArray();
任何想法?
更新
使用导航属性(CMSPages2_1)可以解决问题:
var pages = (from p in ctx.CMSPages2
where p.MenuID == num && p.ParentID == 0
select new
{
URLLevel1 = p.KeywordUrl + "/" + p.FriendlyUrl,
TitleLevel1 = p.LinkTitle,
Level2 = (from o in p.CMSPages2_1
where o.ParentID == p.SitemapExternID
select new
{
URLLevel2 = o.KeywordUrl + "/" + o.FriendlyUrl,
TitleLevel2 = o.LinkTitle,
})
}).ToArray();
答案 0 :(得分:0)
Level2的子查询将返回一个集合,而您似乎正在尝试填充单个对象属性。
尝试使用FirstOrDefault:
var pages = (from p in ctx.CMSPages2
where p.MenuID == num && p.ParentID == 0
select new
{
URLLevel1 = p.KeywordUrl + "/" + p.FriendlyUrl,
TitleLevel1 = p.LinkTitle,
Level2 = ctx.CMSPages2
.FirstOrDefault(q => q.ParentID == p.SitemapExternID)
.Select(x => new
{
URLLevel2 = x.KeywordUrl + "/" + x.FriendlyUrl,
TitleLevel2 = x.LinkTitle,
});
}).ToArray();
<强>更新强>: 我没注意到这是一棵树。
也许尝试将CMSPages2上的导航属性设置为istelf(比如“SubPages”) 做点什么
var pages = (from p in ctx.CMSPages2
where p.MenuID == num && p.ParentID == 0
select new
{
URLLevel1 = p.KeywordUrl + "/" + p.FriendlyUrl,
TitleLevel1 = p.LinkTitle,
Level2 = p.SubPages
.Select(q => new
{
URLLevel2 = q.KeywordUrl + "/" + q.FriendlyUrl,
TitleLevel2 = q.LinkTitle,
});
}).ToArray();