views:

65

answers:

2

I'm using the Mono.CSharp library to emit code. Following another question on SO (http://stackoverflow.com/questions/3407318/mono-compiler-as-a-service-mcs) I managed to get Mono.CSharp evaluating correctly on the Microsoft CLR.

To add flexibility in my app I'd like to be able to customize a query at runtime - by allowing the user to provide a LINQ query as a string that gets parsed and hits the database when executed.

Given this basic snippet of code:

IQueryable<Contact> contacts = GetContacts();
string query = "from contact in contacts
                where contact.Name == \"name\"
                select contact";
var queryableResult = Mono.CSharp.Evaluator.Evaluate(query);

How can I 'inject' the contacts variable into the Mono.CSharp.Evaluator to be evaluated as part of the query? Am I going about this the right way? In the end I either need the resulting Expression or the IQueryable from the 'query' string.

+1  A: 
JeffN825
From a design point that's tightly coupling the code to the DataContext. I'm using NHibernate 3 with Ninject to get a new, clean ISession injected into my MVC controller's constructor for every request. If that's the only route then I can work around it with some static calls, just isn't ideal.
Kevin McKelvin
Let me think some more, and I'm sure there are better ways, but my first thought is to make a ThreadStatic variable in your calling code and reference that from your string evaluated code.
JeffN825
+1  A: 

I didn't try this, but I guess you could use Mono compiler to create a delegate vthat takes IQueryable<Contract> as argument and returns the filtered query. Something like:

IQueryable<Contact> contacts = GetContacts(); 
string query = "new Func<IQueryable<Contact>, IQueryable<Contact>>(contracts =>
                  from contact in contacts 
                  where contact.Name == \"name\" 
                  select contact)"; 
var res = Mono.CSharp.Evaluator.Evaluate(query); 

Then you just need to cast res to an appropriate Func<,> type and invoke it to get the result.

Tomas Petricek