views:

113

answers:

1

Going backwards from SQL to LINQ2SQL is sometimes quite simple. The following statement

SELECT user FROM users WHERE lastname='jones'

translates fairly easily into

from u in users where u.lastname='jones' select u

But how do you get the following SQL generated?

SELECT user FROM users WHERE lastname IN ('jones', 'anderson')
+5  A: 

I had to do a bit of searching to find this, and thought it might be useful to others.

List<string> names = new List<string>() { "jones", "anderson" };

from u in users where names.Contains(u.lastname) select u
Jedidja
You are going to run into a problem with the `Contains` expression not being translateable to SQL, so that won't work if users is a `System.Data.Linq.Table` on a LinqToSql DataContext.
klausbyskov
@klausbyskov: This is not true. Entity Framework / LINQ to Entities is unable to do this in .NET 3.5, but LINQ to SQL will be happy to convert this into SQL. The only gotcha is that the number of elements in the IN( ) clause (the number of elements in the 'name' list) is limited, due to limitations of ADO.NET.
Steven
@klausbyskov: Actually it works just fine - I've run the code and looked at the result in SQL profiler. Did you give me the downvotes?
Jedidja
Ok, I stand corrected.
klausbyskov