I was playing around with LINQPad and was curious how I could implement similar behavior in my own app, namely: how can I allow the user to input a LINQ query against a known database context as a string and then run that query in the application?
For example, if I have the LINQ-to-SQL datacontext for the Northwind database in my application, I want the user to have the ability to type
from cust in Customers
where cust.City == "London"
select cust;
And I’ll return the results of calling .ToList() on this query.
Any ideas/tips/links?
Thanks kindly
Mustafa
The
System.CodeDomnamespace might do what you’re looking for. Check out this blog post:http://blogs.msdn.com/lukeh/archive/2007/07/11/c-3-0-and-codedom.aspx
Though instead of
public static void Mainyou could compile a static method that takes a DataContext class and returns IEnumerable using the provided LINQ query. Or whatever works.Be mindful that everytime you compile code this way you’re creating a new assembly, which would then need to be loaded into your application before you can execute it. Assemblies aren’t garbage collected; if users are going to want to run many, many queries it could lead to a nasty memory leak.
And it’d also be a good idea to be mindful of possible attacks users can do by typing in whatever malicious code they want executed. But I don’t have any rock solid advice for you there.