Search code examples
c#entity-frameworklinqlambdalinq-to-entities

IQueryable: Project columns by their names in linq dynamically at runtime


I have a Dictionary<string, string> Fields that contains propertyNames and property Types.

and I have a query object: IQueryable<T> query = GetQuery();

I am using Typebuilder to build a type dynamically according to the Fields dictionary:

TypeBuilder builder = CreateTypeBuilder("MyDynamicAssembly", "MyModule", "MyType");

DataTable dt = new DataTable();

foreach (var s in Fields)
{
   CreateAutoImplementedProperty(builder, s.Key, Type.GetType(s.Value));
   dt.Columns.Add(s.Key, Type.GetType(s.Value));
}

Type resultType = builder.CreateType();

I want to modify the query object using linq to project only columns that their names are in the Fields dictionary. Something like:

dynamic queryResult = query.Take(10).Select("Don't know how to project here???");

consider the column names are:

string[] columnsNames = Fields.Select(x => x.Key).ToArray();

How can I do this?


Solution

  • Because you're building queries dynamically at run time, you need to build the expression tree dynamically. You can use this library to help with that: https://dynamiclinq.codeplex.com/

    In your case, you can build your .Select clause dynamically like this:

    string[] columnsNames = Fields.Select(x => x.Key).ToArray();
    
    string columns = string.Join(",", columnsNames);
    
    dynamic queryResult = query.Take(10).Select("new (" + columns + ")");
    

    The .Select above is the extension method from that library