简体   繁体   中英

How do you force a .Contains in a Linq to SQL where clause to be done by SQL server?

I have a list of row IDs being used in a Linq to SQL query.

using (var db = new DataContext(dbConnectionString))
{
   ids = new list<long> {"1","2",...};
   var data = (from item in db.GetTable<dataTable>().AsEnumerable()
               where ids.Contains(item.ID)
               select new customDataStructure{}).ToList();
}

In some cases, it passes each of the IDs in the list to SQL as parameters in the format "where ID in (@p0,@p1,...)". In other cases, the query retrieves all records and lets the filter happen in c#. This causes a huge spike in memory usage and possible memory exceptions it the amount of data retrieved is very large.

Is it possible to force the query to execute the where on the SQL server to avoid this issue?

As Evk commented, the AsEnumerable() caused the where to be executed locally, not on the SQL server.

It was being used since I needed lists and dictionaries in the returned type which cause exceptions if you try to build them in an IQueryable.

I altered the query to

using (var db = new DataContext(dbConnectionString))
{
   ids = new list<long> {"1","2",...};
   var data = (from item in db.GetTable<dataTable>()
               where ids.Contains(item.ID)
               select new 
               {
                  name = item.name,
                  subIds = item.subitemIDs
                  ...
               }).AsEnumerable()
               .Select(x=> new customDataStructure
                   {
                      itemname = x.name,
                      subIds = x.subIds.ToList(),
                      ...
                   }).ToList();
}

It let the data collection be done by SQL and then have the needed structure completed after the SQL executes.

Using .Contains() is not what I think you are wanting to use. I think you want to use .Any() which will see if any of the items in your list match a property or column in your table. See below:

var ids = new List<long> {1,2};
var data = (from item in db.GetTable<dataTable>().AsEnumerable()
where ids.Any(m=> m == item.Property)
select new customDataStructure{}).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM