Reputation: 2413
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?
Upvotes: 0
Views: 1049
Reputation: 48972
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
Upvotes: 1