c# - Injecting a variable into the Mono.CSharp.Evaluator (runtime compiling a LINQ query from string) -


i'm using mono.csharp library emit code. following question on (http://stackoverflow.com/questions/3407318/mono-compiler-as-a-service-mcs) managed mono.csharp evaluating correctly on microsoft clr.

to add flexibility in app i'd able customize query @ runtime - allowing user provide linq query string gets parsed , hits database when executed.

given basic snippet of code:

iqueryable<contact> contacts = getcontacts(); string query = "from contact in contacts                 contact.name == \"name\"                 select contact"; var queryableresult = mono.csharp.evaluator.evaluate(query); 

how can 'inject' contacts variable mono.csharp.evaluator evaluated part of query? going right way? in end either need resulting expression or iqueryable 'query' string.

i think have few options:

  1. use static or threadstatic variables exchange data between caller , string based code:

    namespace myns {   public class myclass   {  [threadstatic] // thread static data specific calling thread  public static string myenumerablevariable;    public void dosomething()   {       evaluator.referenceassembly(assembly.getexecutingassembly());       evaluator.run("using myns;")       // run dynamic code       var s = @"return (from contact in myns.myclass.myenumerablevariable contact.name == ""john"" select contact).tolist();";       evaluator.evaluate(s);  } 

    } }

  2. return delegate string code:

      public void dosomething()   {

    // run dynamic code var s = @"return new func<string, iqueryable<myns.model.contact>, ilist>((s,q) => (from contact in q contact.name == s select contact).tolist());"; var func = (func<string, iqueryable<myns.model.contact>, ilist>)evaluator.evaluate(s); var result = func("john", myqueryableofcontactsfromnhibernate);

    }

  3. go full blown route.
  string query = string.format( @"using (var dc = new datacontext())  {   return (from contact in dc.contacts contact.name == ""{0}"" select contact).tolist(); }", "john");  var result = mono.csharp.evaluator.evaluate(query); 


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -