views:

101

answers:

1

I'm working with an application which allows customers to create and import custom tables. I have the need to allow those customers to build dynamic queries against the imported custom tables and I would like to be able to use LINQ to do this.

I'm familiar with how to create Dynamic LINQ queries however all the methods I know of require an existing mapped object on the DataContext object. As users are able to create custom tables at runtime (through dynamic string built SQL) there isn't a mapped object in any DataContext.

Is there a way to dynamically create a DataContext and mapped object at runtime for use with a dynamic Linq query?

Is there some other way to do this without resorting to string built sql?

A: 

There are some T4 templates available for creation of Linq to SQL data classes. Perhaps you can adapt those.

http://www.pnpguidance.net/Post/LINQToSQLCodeGenerationT4TemplatesTutorials.aspx

There are two ways that I can think of to generate the assembly without requiring the Microsoft C# compiler or Visual Studio. The first is to use System.Reflection.Emit to generate a custom assembly. This might be easier than it sounds; have a look at the following add-in for Reflector:

ReflectionEmitLanguage Add-in for Reflector
http://reflectoraddins.codeplex.com/wikipage?title=ReflectionEmitLanguage&referringTitle=Home

What the add-in does is take an existing IL assembly and create C# code that contains the System.Reflection.Emit calls that it would take to generate the same IL that the C# compiler would. So essentially what you would do is create an assembly containing a prototype DataContext, and run this on its methods. You would then have a class (or the better part of one) that will generate the IL assembly directly. All of this code is open-source.

The other thing you could do is try using the Mono C# compiler (which can be called like a service, unlike the Microsoft C# compiler) to generate your IL assembly. The C# compiler is also open-source.

Robert Harvey
That is an interesting idea. I believe that would still require Visual Studio to parse and generate against the T4 template. I could also possibly use another code generator such as CodeSmith to get similar results but as far as I know both would require a compile to get the classes hooked into the DataContext.
Firestrand
@Firestrand, see my edit.
Robert Harvey
So the answer so far is that some type of dynamic compilation must occur in order to build the classes and data context for Linq. There are several resources for dynamic compilation. I will work in that direction.
Firestrand