Working around LinqToSQls “queries with local collections are not supported” exception

后端 未结 4 1962
你的背包
你的背包 2020-12-05 09:32

So, I\'m trying to return a collection of People whose ID is contained within a locally created collection of ids ( IQueryable)

When I specify \"locally created col

相关标签:
4条回答
  • 2020-12-05 10:16

    As the guys mentioned above, converting the ids, which is of type IQueryable to List or Array will solve the issue, this will be translated to "IN" operator in SQL.But be careful because if the count of ids >= 2100 this will cause another issue which is "The server supports a maximum of 2100 parameters" and that is the maximum number of parameters(values) you can pass to "IN" in SQL server.

    Another alternative would be keeping ids as IQueryable and using LINQ "Any" operator instead of "Contains", this will be translated to "EXISTS" in SQL server.

    0 讨论(0)
  • 2020-12-05 10:20

    I was struggling with this problem also. Solved my problem with using Any() instead

    people.Where(x => ids.Any(id => id == x.ID))
    
    0 讨论(0)
  • 2020-12-05 10:21

    If Ids is a List, array or similar, L2S will translate into a contains.

    If Ids is a IQueryable, just turn it into a list before using it in the query. E.g.:

    List<int> listOfIDs = IDs.ToList();  
    var query =  
    from st in dc.SomeTable  
    where listOfIDs.Contains(st.ID)
    select .....
    
    0 讨论(0)
  • 2020-12-05 10:22

    I'm sorry but the answers here didn't work for me as I'm doing dynamic types further along.

    What I did was to use "UNION" in a loop which works great. Here's how:

    var firstID = cityList.First().id;
    var cities = dc.zs_Cities.Where(c => c.id == firstID);
    foreach(var c in cityList)
    {
      var tempCity = c;
      cities = cities.Union(dc.zs_Cities.Where(cty => cty.id == tempCity.id));
    }
    
    0 讨论(0)
提交回复
热议问题