EF Core - Where clause on multiple field in object list
Hi everybody
I'm using sql through EF Core, here at work, and I have a problem querying multiple results from a table
In SQL, I've got that table of
Foo
with an index on field a
and b
In my code, I've got a list of Bar
containing, quite conveniently, two field a
and b
I'd like to do something along the line of
But where foo could match with any element of an enumerable of bar
My colleague suggest something looking like this
Super, that works
But...
It's slow as heck
Our guess is that it try out every row in the table foo?
Like, he can't really know the result of foo.a + foo.b so it does it for every single row before checking it for a match inside of stringifiedBar?
How would one do that query properly?11 Replies
?
Ah, wait, an enumerable of
Bar
s
Something like thatYes, I may have miss explained the problem
Both A and B should be equal for a matching record
Here, if I read that line correctly, the A from Foo could match with a first Bar and the B from Foo could match with the A of a second Bar, wouldn't it?
I'll give it a shot anyway, thank you 🙂
Right, so
Foo
's A and B should match those of any Bar
in a list?
thenAngius
REPL Result: Success
Result: WhereArrayIterator<Foo>
Compile: 495.947ms | Execution: 91.285ms | React with ❌ to remove this embed.
mmmmmm, that's actually great..
I wonder why we didn't do that anywhere in our code base rather that the ugly stringified trick 🤔
Thanks a lot @ZZZZZZZZZZZZZZZZZZZZZZZZZ 🙏
I'll try that out and close the thread once it works
I have an idea as to why, but I don't want to be rude to your coworkers 😛
mmmm, it seems like ef core can't translate the query
or am I just bad at writting?
That looks close enough, though
Huh, it should work
What's the database you're using?
You could try splitting it into three
.Where(...Any())
sI was gonna say
You expect passing a list of complex objects to EFC works? 😄
It works for Linq yee, but cannot be expressed in sql
Nah, it can work using
IN [1, 2, 3, 4, 5]
or whatever the syntax is
Depends on the db though
Not every db will support thatThat's not a complex type though
Ofc you can do it with ints, strings and what not, but not with a complex type where 1 element consists of 3 columns / properties
Edit:
Though with SQL Server json columns and json functions (OPENJSON() and stuff) it could with some black magic be possible maybe, though I imagine not
I can think of two ways
1 (Slow, not really nice):
If its a small list of
lignesClients
of like 2 - 5 elements, you could build Expressions at runtime that will basically become
2 (Fast, pretty cool, yo!):
Hoping that your lignesClients
is an IEnumerable (or array or list) that comes from an IQueryable query, and making sure it stays an IQueryable, so that you can make it a sub-query within your query here with what @ZZZZZZZZZZZZZZZZZZZZZZZZZ suggested, which should translate into something like