views:

40

answers:

2

I need to build a LINQ query that allows me to vary the where clause on a joined table but can't find a way to do it.

A simplified example of the two queries I'm constructing are:

var myQuery = from tab1 in context.Table1
              join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
              where tab1.TypeCode == 3
                    tab2.SomeID == 4 &&  
              select tab1.ID;

var myQuery2 = from tab1 in context.Table1
              join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
              where tab1.TypeCode == 3
                    tab2.SomeOtherID == 4 &&  
              select tab1.ID;

The only difference between them being the tab2.SomeID where clause changes to tab2.SomeOtherID.

If the changing where clause was being applied to tab1 I could just add a .Where to the query but how do I use a common query and specify a different tab2 where clause?

+2  A: 

Dynamically Composing Expression Predicates

or

alt text

You need something like this? Use the Linq Dynamic Query Library (download includes examples).

Check out ScottGu's blog for more examples.

Pranay Rana
I've used DynamicLinq in the past to good effect but in this case I'd like to keep my query strongly typed.
sipwiz
than use PredicateBuilder will work for you link alreay there in answer
Pranay Rana
+1  A: 

You can have optional parameters in queries:

int? someID = null;
int? someOtherID = 4;

var myQuery = from tab1 in context.Table1 
              join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID 
              where tab1.TypeCode == 3 
               && (someID == null || tab2.SomeID == someID)
               && (someOtherID == null || tab2.SomeOtherID == someOtherID)
              select tab1.ID;

Linq-to-SQL will eliminate the parts that can be evaluated client-side from the query, so in the above example the where clause will filter on tab1.TypeCode and tab2.SomeOtherID.

KristoferA - Huagati.com
I actually used that approach and thought that L2S would remove the redundant conditional. However it didn't and while having 1 == 0 in the SQL where wouldn't matter I was hoping there would be a cleaner way.
sipwiz
Check your query again - unless you used Linq-to-SQL's "CompiledQuery", L2S should eliminate the unnecessary parts of the query. (I.e. the parts that can be evaluated client-side)
KristoferA - Huagati.com
L2S isn't that sophisitcated at elimintating unecessary parts of the query. I had to reduce the expressions is the LINQ to true or false to get them elimintated. Despite that this was the best approach I could find.
sipwiz