How to turn this LINQ query to lazy loading
I would like to make a certain select item to lazy load latter in my linq query. Here is my query
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.p开发者_Go百科ost_titleslug,
p.post_votecount,
FavoriteCount = context.PostVotes.Where(x => x.PostVote_postid == p.post_id).Count() //this should load latter
};
I have deleted the FavoriteCount item in the select query and would like it to ba added later based on certain conditions. Here is the way I have it lazy loaded
if (GetFavoriteInfo)
{
posts = posts.Select(x => new { FavoriteCount = context.PostVotes.Where(y => y.PostVote_postid == x.post_id).Count() });
}
I am getting a syntax error with this the above query. How do I fix this
When you delete the FavoriteCount
in the earlier query, the anonymous type that gets assigned to posts
doesn't have that field anymore; then in the second query you're creating another anonymous type that only has a FavoriteCount
in it - so when you try to re-assign that to posts
you get an incompatible types error.
One way to do this would be to leave the FavoriteCount
in the first query, but make it FavoriteCount = -1
(or some other value to indicate it hasn't loaded yet), and then in the second one you can do:
posts = posts.Select(p => new { // reassign existing stuff,
p.post_date,
p.post_id,
p.post_titleslug,
p.post_votecount,
FavoriteCount = context.etc.etc.
});
You have to do the reassignment because anonymous types are immutable; one way around that would be to make a PostInfo
class with those fields, then you can just set the FavoriteCount
in the second query.
1.- the type that you are projecting on the first var is not the same type on the second assigment since first one is an anonymus type
you can try this
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 = GetFavoriteInfo?context.PostVotes.Where(x => x.PostVote_postid == p.post_id).Count():null //this should load latter
};
This blog entry will help you. One more thing, you can enable/disable lazy loading by using the following property of Data Context object.
context.DeferredLoadingEnabled = false;
精彩评论