I have two classes:
public class Contratos
{
public int EntidadeFinanceiraId { get; set; }
[Column("Nome")]
public EntidadesFinanceiras entidadeFinanceira { get; set; }
}
public class EntidadesFinanceiras
{
[Key]
public int ID { get; set; }
public string Nome { get; set; }
}
and want to dynamically filter the Contratos list based on Contratos.entidadeFinanceira.Nome. This is part of a method that filters a list based on a property selected by the user.
public IQueryable<Models.Contratos> applyLambdaFilter(string val, string col, string oper, IQueryable<Models.Contratos> contratosList)
{
if (!string.IsNullOrWhiteSpace(val))
{
string typeName;
string columnName;
Type propType;
string[] propName = col.Split(new[] { '.' });
if (propName.Count() > 1)
{
typeName = "GAcordos.Models." + propName[0];
columnName = propName[1];
propType = Type.GetType("GAcordos.Models.Contratos").GetProperty(propName[0]).PropertyType.GetProperty(columnName).PropertyType;
}
else
{
typeName = "GAcordos.Models.Contratos";
columnName = propName[0];
propType = Type.GetType(typeName).GetProperty(columnName).PropertyType;
}
if (propType != null)
{
var fixedItem = Comparators.getFixedItemWithType(val, propType);
var param = Expression.Parameter(typeof(GAcordos.Models.Contratos), "x");
var body = Expression.Equal(Expression.PropertyOrField(param, col.ToString()), fixedItem, false, Type.GetType("GAcordos.Helpers.Comparators").GetMethod(oper, new Type[] { propType, propType }));
var lambda = Expression.Lambda<Func<GAcordos.Models.Contratos, bool>>(body, param);
contratosList = contratosList.Where(lambda.Compile()).AsQueryable();
}
}
return contratosList;
}
When a method does this, it throws an exception 'entidadeFinanceira.Nome' is not a member of type 'GAcordos.Models.Contratos' in the line
var body = Expression.Equal(Expression.PropertyOrField(param, col.ToString()), fixedItem, false, Type.GetType("GAcordos.Helpers.Comparators").GetMethod(oper, new Type[] { propType, propType }));
But if I write the expression directly:
contratosList = contratosList.Where(x => x.entidadeFinanceira.Nome == val);
It works great.
So how can I build the lambda expression x => x.property.property == constVal?