✅ EF two Select in a query problem when using ToList().
I want to reduce two ToList() to one. But it gives me error.
System.InvalidOperationException: The LINQ expression 'ProjectionBindingExpression: 0' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
14 Replies
seems to me like you should really be starting this query from the
Posts
table not votes, considering you want to get the post
Yeah, I should do that. But I want to know why it gives me a run time error. Which part was wrong I still don't understand.
EF can't translate the
g.First().targetPost
into sql more than likelyNah, the code I gave works. In the second select, I am able to choose between post and karma but it throws an error if I don't write ToList() before it
If I write ToList(), the result is what I expected. It must be something about Iqueryable or something, no idea why
Not too sure without seeing what kind of sql its generating for the case that works
either way, id rewrite the query to make a bit more sense
of course. It's the second time I am facing this select problem. It gets more frustrating because I don't know why. And it doesn't tell me anything
any time you run into that its because ef cannot translate the query into sql, so something you are doing does not make sense in the context of sql
Ouch
Lemme rewrite it first
This worked for some reason. Obviously I will improve it. This is too raw.
Let me know if you reviewed it.
you can probably remove both of the selects by just ordering by the votes, but keeping it doesn't really affect much
"Doesn't really affect much"... this is huge lol
readability is very important after all
Thank you kind stranger. You saved my day.
Or morning anyway. It's 3am again.
Btw, do you have any idea to make this better;
maybe
Yeah, a single function seems like an obvious choice
Btw, what's with the ProjectTo? Never seen this use before.
extension method from automapper, i think it looks nicer than having to wrap the entire query in
_mapper.ProjectTo<T>(query)
As long as it doesn't affect speed. It looks cool tho. I will use it from now on. I hope the extension isn't trying to be smart and be dead weight.
Thank you again