I'm working on this currently, and I recommend using System.Linq.Expressions.Expression
, Lambda
, and a little Reflection
for this.
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);
EXAMPLE Equals
// 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);
Continuation code ...
// 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