Entity Framework providing column names as string

2019-04-20 15:28发布

问题:

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.

回答1:

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.



回答2:

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);


回答3:

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.
  }

}