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.
I think you have a few options:
Use static or ThreadStatic variables to exchange data between the caller and you string based code:
}
}
Return a delegate from your string code:
// run the dynamic code
var s = @"return new Func<string, IQueryable<MyNs.Model.Contact>, IList>((s,q) => (from contact in q where contact.Name == s select contact).ToList());";
var func = (Func<string, IQueryable<MyNs.Model.Contact>, IList>)Evaluator.Evaluate(s);
var result = func("John", myQueryableOfContactsFromNHibernate);
}