Luk*_*101 5 c# linq linq-to-entities lazy-loading
我想在我的linq查询中做一个特定的选择项来延迟加载后者.这是我的查询
var posts = from p in context.post
where p.post_isdeleted == false && p.post_parentid == null
select new
{
p.post_date,
p.post_id,
p.post_titleslug,
p.post_votecount,
FavoriteCount = context.PostVotes.Where(x => x.PostVote_postid == p.post_id).Count() //this should load latter
};
Run Code Online (Sandbox Code Playgroud)
我已经删除了select查询中的FavoriteCount项,并希望稍后根据某些条件添加它.这是我懒惰加载的方式
if (GetFavoriteInfo)
{
posts = posts.Select(x => new { FavoriteCount = context.PostVotes.Where(y => y.PostVote_postid == x.post_id).Count() });
}
Run Code Online (Sandbox Code Playgroud)
我在上面的查询中遇到语法错误.我该如何解决
当您在之前的查询中删除 时FavoriteCount,分配给的匿名类型posts不再具有该字段;然后在第二个查询中,您将创建另一个只有a 的匿名类型FavoriteCount- 因此,当您尝试将其重新分配给posts您时,您会收到不兼容的类型错误。
执行此操作的一种方法是将FavoriteCount第一个查询中的 留在其中,但将其设置为FavoriteCount = -1(或其他一些值来指示它尚未加载),然后在第二个查询中您可以执行以下操作:
posts = posts.Select(p => new { // reassign existing stuff,
p.post_date,
p.post_id,
p.post_titleslug,
p.post_votecount,
FavoriteCount = context.etc.etc.
});
Run Code Online (Sandbox Code Playgroud)
您必须重新分配,因为匿名类型是不可变的;解决这个问题的一种方法是使用这些字段创建一个类,然后您可以在第二个查询中PostInfo设置。FavoriteCount