LINQ to SQL - Dynamically Constructing Queries - Um... No!

time to read 2 min | 336 words

Mike Taulty is talking about constructing queries dynamically in Linq to SQL. Sorry, but my response to that is Yuck! Here is the code that he shows:

  NorthwindDataContext ctx = new NorthwindDataContext("server=.;database=northwind");

   var query = from c in ctx.Customers
               where c.Country == "Germany"
               select c;

   if (RuntimeCriterionOneApplies()) 
   {
    query = from c in query
            where c.City == "Berlin"
            select c;
   }

   if (RuntimeCriterionTwoApplies())
   {
    query = from c in query
            where c.Orders.Sum(o => o.Freight) > 100
            select c;
   }

   foreach (Customer c in query)
   {
    Console.WriteLine(c.CustomerID);
   }

This is not constructing queries dynamically, it is choosing a query dynamically. This isn't what I talk about when I am talking about constructing a query dynamically. You can look here as what I consider a complex query that is being constructed dynamically.

Mike, how would you handle that scenario in Linq?

Update:  I really should pay more attention when I am reading the code. Sorry Mike, the code that you have will work for the scenario that I have. I don't think that the syntax is very elegant for this scenario, but it will work. I missed the "from q in query" and read is as if a new query were constructed in each if.