Compiling query with IQueryable<bool> return value

2015-07-04 c# linq

I have a list of Post Ids and I'm trying to return vote status of the current user for each post (true if the user has voted for that post and false if he has not). Every thing seems ok to me but I'm getting two errors.

public static Func<DatabaseDataContext, string, int[], IQueryable<bool>>
    GetUserVoted = CompiledQuery.Compile((DatabaseDataContext db, string UserId, int[] PostIds)
    => (from p in PostIds
        select new 
        {
           db.Votes.Any(v=> v.PostId==p && v.UserId == UserId)
        })
    );

I'm getting 2 errors:

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

And

Cannot implicitly convert type 'System.Func< DatabaseDataContext,string,int[],System.Collections.Generic.IEnumerable>' to 'System.Func< DatabaseDataContext,string,int[],System.Linq.IQueryable>'. An explicit conversion exists (are you missing a cast?)

Answers

If you are going to use Anonymous Type, then its members should have a name. You're missing a name like HasAnyVote:

 select new 
        {
           HasAnyVote = db.Votes.Any(v=> v.PostId==p && v.UserId == UserId)
        })

Or use it directly :

(from p in PostIds
select db.Votes.Any(v=> v.PostId==p && v.UserId == UserId))
.AsQueryable<bool>()

Related