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

后端 未结 12 2062
别那么骄傲
别那么骄傲 2020-12-05 18:23

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

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

by

12条回答
  •  甜味超标
    2020-12-05 19:11

    i think the proper way to do it is

    var result = from loc in Location
                 where loc.Country = _country
                 where loc.City = _city
                 where loc.Address = _address
                 select loc
    

    It looks unoptimized but the query provider will go out and do the optimization when it transforms the query to sql. When using tuples or other classes, the query provider doesnt know how to transform them into sql and that what causes the NotSupportedException

    -edit-

    If you have multiple key tuples i think you have to loop through them all and do the above query for each one. again, that might seem underoptimized, but the query for retriving all the locations in a single query would probably end up beeing quite long:

    select * from locations 
    where (locations.Country = @country1 and locations.City = @city1, locations.Adress = @adress1)
    or (locations.Country = @country2 and locations.City = @city2, locations.Adress = @adress2)
    or ...
    

    The fastest way of doing it is probably to do the simple queries, but send them as a single sql script and use multiple result sets for actually getting each value. Im not sure you can get EF to do that though.

提交回复
热议问题