Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities - where..in clause with multiple columns

Tags:

I'm trying to query data of the form with LINQ-to-EF:

class Location {     string Country;     string City;     string Address;     … } 

by looking up a location by the tuple (Country, City, Address). I tried

var keys = new[] {     new {Country=…, City=…, Address=…},     … }  var result = from loc in Location              where keys.Contains(new {                  Country=loc.Country,                   City=loc.City,                   Address=loc.Address              } 

but LINQ doesn't want to accept an anonymous type (which I understand is the way to express tuples in LINQ) as the parameter to Contains().

Is there a "nice" way to express this in LINQ, while being able to run the query on the database? Alternately, if I just iterated over keys and Union()-ed the queries together, would that be bad for performance?

like image 760
millimoose Avatar asked Aug 02 '11 13:08

millimoose


People also ask

Can we use multiple where clause in LINQ?

Filter collections using Where clause in C#. A single query expression may have multiple where clauses.

Is LINQ faster than stored procedures?

Stored procedures are faster as compared to LINQ query since they have a predictable execution plan and can take the full advantage of SQL features. Hence, when a stored procedure is being executed next time, the database used the cached execution plan to execute that stored procedure.

Which is correct about LINQ to Entities?

LINQ to Entities provides Language-Integrated Query (LINQ) support that enables developers to write queries against the Entity Framework conceptual model using Visual Basic or Visual C#. Queries against the Entity Framework are represented by command tree queries, which execute against the object context.


1 Answers

How about:

var result = locations.Where(l => keys.Any(k =>                      k.Country == l.Country &&                      k.City == l.City &&                      k.Address == l.Address)); 

UPDATE

Unfortunately EF throws NotSupportedException on that, which disqualifies this answer if you need the query to run on DB side.

UPDATE 2

Tried all kinds of joins using custom classes and Tuples - neither works. What data volumes are we talking about? If it's nothing too big, you could either process it client-side (convenient) or use unions (if not faster, at least less data is transmitted).

like image 179
Jacek Gorgoń Avatar answered Oct 02 '22 22:10

Jacek Gorgoń