Given a property foo
of an entity bar
for which the entity set contains a large number of values, how can we check for the absence (from bar
) of any value in an arbitrary list of values, using LINQ-to-Entities?
For example:
bar
containsALPHA
andBETA
.- We have a list of three items:
[ALPHA, BETA, GAMMA]
which we want to send to the EF backend (DBMS). We expect the backend to reply with a single scalar result (1 or 0 / true or false). In this case, it would return 0, since at least one value is absent (GAMMA
). - If all values from the list are in the entity set, the query would return 1. For example, when the list is:
[ALPHA, BETA]
or simply[ALPHA]
or[BETA]
. - We definitely don't want to transfer the whole entity set to the EF client.
- We definitely don't want to issue multiple queries for each value in the list.
Example dynamic T-SQL:
select case when not exists (
select * from (
select 'ALPHA' foo
union select 'BETA' foo
union select 'GAMMA' foo) a
left join (select distinct foo from bar) b
on a.foo = b.foo
where b.foo is null)
then 1
else 0
end;
How could we formulate a LINQ-to-Entity query that would generate this SQL query (or equivalent)?
Note: I wrote this SQL query in the most natural way I could think of (it literally reads like "check that there is no value in the list for which there is no corresponding value in the bar
table"). It's very likely there's a better way to do this.