Linq2Sql - Storing Complex Linq Queries for future dynamic execuction - raw text - possible?
c#, linq, linq-to-sql
Solution
Perhaps the Dynamic LINQ Library (in the MSDN samples) would help?
In particular, usage like:
This should work with any `IQueryable<T>` source - including LINQ-to-Objects simply by calling `.AsQueryable()` on the sequence (typically `IEnumerable<T>`).
Problem
I am having a lot of fun with Linq2Sql. Expression Trees have been great, and just the standard Linq2Sql syntax has been a lot of fun. I am now down to part of my application where I have to somehow store queries in a database, that are custom for different customers that use the same database and same tables (well, view, but you know what I mean). Basically, I cant hard-code anything, and I have to leave the query language clear text so someone can write a new where-clause type query. So, if that description was harsh, let me clarify: In a previous version of our application, we used to do direct SQL calls to the db using raw SQL. Yea. it was fun, dirty, and it worked. We would have a database table fulled of different criteria like ``` (EventType = 6 and Total > 0) ``` or a subquery style ``` (EventType = 7 AND Exists ( select * from events as e1 where events.EventType = e1.EventType and e1.objectNumber = 89) ) ``` (sql injection anyone?) In Linq2Sql, this is a little more challenging. I can make all these queries no problem in the CLR, but being able to pass dynamic where criterias to Linq is a little more challenging, especially if I want to perform a sub query (like the above example). Some ideas I had: Get the raw expression, and store it --- but I have no idea how to take the raw text expression and reverse it back to executable to object expression. Write a SQl like language, and have it parse the code and generate Linq Expression -- wow, that could be a lot of fun I am quite sure there is no `SomeIqueryable.Where("EventType = 6 and Total > 54")`. I was reading that it was available in beta1, but I don't see how you can do that now. ``` var exp2 = context.POSDataEventView.Where("EmployeeNumber == @0", 8310); ``` This would be the easiest way for me to deploy.. I think. Store serialized Expressions -- wow.. that would be confusing to a user trying to write a query --- hell, I'm not sure I could even type it all out. So, I am looking for some ideas on how I can store a query in some kind of clear text, and then execute it against my Linq2Sql objects in some fashion without calling the ExecuteSQL. I want to use the LinqObjects. P.S. I am using pLinqo for this application if that helps. Its still linq2sql though. Thanks in advance!