Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.post_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

like image 598
Luke101 Avatar asked Oct 15 '22 04:10

Luke101


1 Answers

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.

like image 117
tzaman Avatar answered Nov 14 '22 14:11

tzaman