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.

2
  • 1
    you mean selecting the column or filtering by that column? In your example you are no using _col1 after assigning it. Please specify... Commented Oct 21, 2011 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 Commented Oct 21, 2011 at 19:29

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

error when getting a collection of items instead of just one.
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);

2 Comments

is there some reference for this? what does "x" mean?
@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, stackoverflow.com/questions/7246715/….
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.
  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.