Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework providing column names as string variable

I'm looking for way to get something like this:

string _col1 = "first name";
string _name;
var query = from c in ctx.Customers select c;
_name = query.FirstOrDefault().[_name];

As far as I can see I can only get strongly typed field names but I would like to provide them as string variables.

like image 518
Andy Avatar asked Oct 21 '11 19:10

Andy


1 Answers

You need to use reflection for this. If you are trying to filter by a dynamicly selected column, you can try something like this:

string propertyName
string keyword

ParameterExpression parameter = Expression.Parameter(typeof(YourType), "x");
Expression property = Expression.Property(parameter, propertyName);
Expression target = Expression.Constant(keyword);
Expression containsMethod = Expression.Call(property, "Contains", null, target);
Expression<Func<YourType, bool>> lambda =
   Expression.Lambda<Func<YourType, bool>>(containsMethod, parameter);

var companies = repository.AsQueryable().Where(lambda);

I what you are trying to do is selecting a particular column, then you can use the same principle for generating the lamba expression and using it in the select (minus the condition)

var companies = repository.AsQueryable().Where(whatever).Select(lambda);
like image 134
AJC Avatar answered Sep 19 '22 19:09

AJC