www.allpaul.com

I needed somewhere to put all this stuff
Welcome to www.allpaul.com Sign in | Join | Help
in Search

Programming

Linq to entities "IN" query

Recently I was looking for a way to build the following SQL query using the entity framework 

   1:  SELECT * FROM tbl_Registrations WHERE [ID] IN (1, 2, 3, 4, 5)

But, turns out, that is not very easy. I thought of three different approaches. To begin, I have a entity set Registrations of entities Registration.  These Registration entities have a property ID (int).  So I tried,

1. Create an int array of the IDs and use the Intersect operator.  But, and there may be other reasons, the Intersect operator doesn't accept Lambda expressions and without it the result would only be a list of ints, which I already had.

2. Create an int array (Or List<int> or List<MyTypeWithIntProperty>) then join the array/list to my Registrations on the ID equal to the value in the array or list.  That doesn't work.

3. Use the Any operator with the same list/array from #2 with a Lambda expression.  That didn't work either.

Normally, I would then just hit the newsgroup and do a search, but I couldn't search on the word IN and the word Any yielded more than 2000 results. After plugging through the almost random search results I finally came across another gem from Colin Meek. The post shows how to achieve the desired results using a utility method to construct an expression of concatenated or statements.  So, my original query gets translated into

      (r.ID == 1 || r.ID == 2 || r.ID == 3 ...)

To clarify HOW to implement his example, I did the following

   1:  int[] regIds = { 1, 2 };
   2:   
   3:  var regs = (from r in se.Registrations
   4:                          select r)
   5:             .Where(Extensions.
   6:             BuildContainsExpression<Registration, int>(e => e.ID, regIds));

 

It should be noted that I have a class that contains all my extension and helper methods called Extensions. Hopefully, by me writing about this it will help anyone looking for way to implement a "IN" query in Linq to entities.

Good luck

 

Only published comments... Sep 15 2008, 08:02 PM by paully21

About paully21

 

Powered by Community Server (Non-Commercial Edition), by Telligent Systems