12

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.

Yuck
  • 49,664
  • 13
  • 105
  • 135
Andy
  • 155
  • 1
  • 3
  • 12
  • 1
    you mean selecting the column or filtering by that column? In your example you are no using _col1 after assigning it. Please specify... – AJC Oct 21 '11 at 19:25
  • I have to put the column name based on the string value from list of strings so it's not for filtering – Andy Oct 21 '11 at 19:29

3 Answers3

20

I'm not sure if EF provides you with a way to get a property value based on the string name of the property, but you can use reflection.

string name = typeof(Customer)
    .GetProperty("first name")
    .GetValue(query.First(), null) as string;

I'm guessing the EF class you're dealing with is called Customer.

Yuck
  • 49,664
  • 13
  • 105
  • 135
Ricky Smith
  • 2,379
  • 1
  • 13
  • 29
5

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);
AJC
  • 1,853
  • 1
  • 17
  • 28
  • is there some reference for this? what does "x" mean? – Matt Aug 19 '13 at 16:13
  • @Matt "x" is for the lambda expression, as in `x => x.Property` it could be anything. The reference, I got from a question I asked, http://stackoverflow.com/questions/7246715/use-reflection-to-get-lambda-expression-from-property-name. – AJC Aug 28 '13 at 00:23
0

For some kind of reason it won't work for me.

That's my similar working solution:

string name = null;

// Select the PropertyInfo of the column.
PropertyInfo propertyInfo = query.First().GetType().GetProperty("first name");

if (propertyInfo != null)
{
  try
  {
    // Select the content of the column.
    name = pi.GetValue(query.First(), null).ToString();
  }
  catch (Exception)
  { 
    // Continue with null-string.
  }

}

Christoph Brückmann
  • 1,373
  • 1
  • 23
  • 41