I am working with this currently, and recommend using System.Linq.Expressions.Expression
, Lambda
and a little bit of Reflection
for that reason.
Example:
string campo = "Campo";
string valor = "valor";
// recupera o objeto IQueryable da Context do EF
IQueryable<Empresa> query = db.EMPRESA;
// cria alias do objecto Lambda
ParameterExpression param = Expression.Parameter(typeof(Empresa), "x");
// obtem tipo da propriedade
Type type = typeof(Empresa).GetProperty(campo).PropertyType;
// cria Expression para o campo
MemberExpression propertyExpression = Expression.PropertyOrField(param, campo);
// cria Expression para o valor
ConstantExpression valueExpression = Expression.Constant(Convert.ChangeType(valor, type), type);
EQUALS EXAMPLE
// cria predicate Lambda Expression
var predicate = Expression.Lambda<Func<Empresa, bool>>(
// aplica tipo de Filtro, no caso do exemplo Equal (campo == valor)
Expression.Equal(propertyExpression, valueExpression)
, param);
EXAMPLE Contains (LIKE)
MethodInfo methodInfo = type.GetMethod("Contains", new[] { type });
var predicate = Expression.Lambda<Func<Empresa, bool>>(
// aplica tipo de Filtro, no caso do exemplo Contains (LIKE campo '%valor%')
Expression.Call(propertyExpression, methodInfo, valueExpression)
, param);
Code continuation...
// adiciona predicate ao where da query
query = query.Where(predicate);
// executa a consulta no banco de dados
var result = query.ToList();
Source: Use string as field name in LINQ
thank you very much, Fernando!
– AndreR
@For the record, you can only choose one answer as correct.
– Jéf Bueno