简体   繁体   中英

Linq to SQL and Collection operations

I have a Dictionary which I'd like to use like an IN clause within a SQL query.

I have a Linq-To-SQL query where I would like to use this Dictionary's Keys to check fields in the rows for the query.

Eg

bool result = DataContext.Table.Any(res => MyDictionary.ContainsKey(res.field1)); 

In effect this is similar to

    exists(select * from Table where field1 in (select id from DictionaryKeys)) 

where DictionaryKeys would be an expansion of the Keys into their own table.

Unfortunately I get

System.NotSupportedException was unhandled
Message="Method 'Boolean ContainsKey(System.String)' has no supported translation to SQL."
Source="System.Data.Linq"

I understand the error, but I'm struggling to think around the problem to a different solution.

Edit: I'm connecting to SQL 2005. Looks like this is a connection provider issue, then, because Marc's suggestion to translate to a List doesn't work for me.

Any ideas?

Try putting the keys into a simple list and using Contains:

var keys = MyDictionary.Keys.ToList();

DataContext.Table.Any(res => keys.Contains(res.field1));

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