I realize there have been a ton of posts related to this and I've researched extensively and can't seem to figure this out. It should be super simple. I simply need to generate a column domain with a dynamic column name. Something like
public IEnumerable<ColumnEntity> GetColumnDomain(string column)
{ List<ColumnEntity> columnEntities = new List<ColumnEntity>();
var query = db.CITATIONs.Select(m => m."column").Distinct();
....
}
Where "column" is the dynamic parameter value. I started building and expression tree to dynamically generate the query expression
ParameterExpression pe = Expression.Parameter(typeof(CITATION), "c");
Expression theColumn = Expression.Property(pe, typeof(string).GetProperty(column));
But that is about it. Thanks in advance
Use the Expression.PropertyOrField()
method to generate the member access. You'll also need to know the type of the column as well or it just won't work.
This could all be generalized into this generic method:
public static Expression<Func<TSource, TResult>>
GenerateSelector<TSource, TResult>(string propertyOrFieldName)
{
var parameter = Expression.Parameter(typeof(TSource));
var body = Expression.Convert(
// generate the appropriate member access
Expression.PropertyOrField(parameter, propertyOrFieldName),
typeof(TResult)
);
var expr = Expression.Lambda<Func<TSource, TResult>>(body, parameter);
return expr;
}
Then you could just do:
public IEnumerable<ColumnEntity> GetColumnDomain<TColumn>(string column)
{
var query = db.CITATIONs
.Select(GenerateSelector<CITATION, TColumn>(column))
.Distinct();
// ...
}