Como construo uma árvore de expressão LINQ que se compara a um objeto genérico?
-
04-07-2019 - |
Pergunta
Eu tenho um iQueryable e um objeto do tipo T.
Eu quero fazer iQueryable (). Onde (o => o.getProperty (fieldName) == ObjectOftypet.getProperty (FieldName))
assim ...
public IQueryable<T> DoWork<T>(string fieldName)
where T : EntityObject
{
...
T objectOfTypeT = ...;
....
return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}
FYI, GetProperty não é uma função válida. Eu preciso de algo que desempenhe essa função.
Estou tendo um cérebro de sexta -feira à tarde derreter ou isso é uma coisa complexa a se fazer?
ObjectOftypet, posso fazer o seguinte ...
var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();
O que funciona perfeitamente, agora só preciso da segunda parte:
Retornar alguma forma (). Onde (o => O.GetProperty (nome do campo) == MatchValue);
Solução
Igual a:
var param = Expression.Parameter(typeof(T), "o");
var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));
var body = Expression.Equal(
Expression.PropertyOrField(param, fieldName),
Expression.PropertyOrField(fixedItem, fieldName));
var lambda = Expression.Lambda<Func<T,bool>>(body,param);
return source.Where(lambda);
Eu iniciei um blog que cobrirá vários tópicos de expressão, aqui.
Se você tiver algum problema, outra opção é extrair o valor de objectOfTypeT
primeiro (usando reflexão) e depois use esse valor no Expression.Constant
, mas eu suspeito que vai ficar bem "como está".
Outras dicas
Pelo que posso ver até agora, terá que ser algo como ...
IQueryable<T>().Where(t =>
MemberExpression.Property(MemberExpression.Constant(t), fieldName) ==
ParameterExpression.Property(ParameterExpression.Constant(item), fieldName));
Embora eu possa fazer com que isso compile, não está executando a maneira como é necessária.
A respeito:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public Func<T, TRes> GetPropertyFunc<T, TRes>(string propertyName)
{
// get the propertyinfo of that property.
PropertyInfo propInfo = typeof(T).GetProperty(propertyName);
// reference the propertyinfo to get the value directly.
return (obj) => { return (TRes)propInfo.GetValue(obj, null); };
}
public void Run()
{
List<Person> personList = new List<Person>();
// fill with some data
personList.Add(new Person { Name = "John", Age = 45 });
personList.Add(new Person { Name = "Michael", Age = 31 });
personList.Add(new Person { Name = "Rose", Age = 63 });
// create a lookup functions (should be executed ones)
Func<Person, string> GetNameValue = GetPropertyFunc<Person, string>("Name");
Func<Person, int> GetAgeValue = GetPropertyFunc<Person, int>("Age");
// filter the list on name
IEnumerable<Person> filteredOnName = personList.Where(item => GetNameValue(item) == "Michael");
// filter the list on age > 35
IEnumerable<Person> filteredOnAge = personList.Where(item => GetAgeValue(item) > 35);
}
Essa é uma maneira de obter valores de propriedades por string sem usar consultas dinâmicas. A desvantagem é que os valores de Al serão encaixotados/não caixas.