What is equivalent GetPropValue<T> method in L2E?
-
05-07-2019 - |
Question
I´m have a problem using EF for my data model.
I have this code in my method:
listaPaginada = sortOrder.Equals("asc") ?
_cadastroServ.SelecionaNotasFiscais(idParceiro).OrderBy(i => i.GetType().GetProperty(query)) :
_cadastroServ.SelecionaNotasFiscais(idParceiro).OrderByDescending(i => i.GetType().GetProperty(query));
i´m using the same method hear to:
Func<NotaFiscal, bool> whereClause = (i => i.GetPropValue<string>(sortName).Contains(query));
listaPaginada = sortOrder.Equals("asc", StringComparison.CurrentCultureIgnoreCase) ?
_cadastroServ.SelecionaNotasFiscais(idParceiro).Where(whereClause).OrderByDescending(i => i.GetPropValue<IComparable>(sortName)) :
_cadastroServ.SelecionaNotasFiscais(idParceiro).Where(whereClause).OrderBy(i => i.GetPropValue<IComparable>(sortName));
In L2SQL the method GetPropValue exists, but in L2E not.
Someone knows a similar method in L2E ? or knows how to solve this ?
Regards[]
Solution
I'm not familiar with GetPropValue
in LINQ-to-SQL. Are you sure it exists? That said, it's easy enough to conjure up what this method is doing and write accordingly:
static class ObjectExtensions {
public static T GetPropValue<T>(this object value, string propertyName) {
if (value == null) { throw new ArgumentNullException("value"); }
if (String.IsNullOrEmpty(propertyName)) { throw new ArgumentException("propertyName"); }
PropertyInfo info = value.GetType().GetProperty(propertyName);
return (T)info.GetValue(value, null);
}
}
Usage:
public class Test {
public string Name { get; set; }
public int Number { get; set; }
}
Test test = new Test() { Name = "Jenny", Number = "8675309" };
Console.WriteLine(test.GetPropValue<string>("Name"));
Console.WriteLine(test.GetPropValue<int>("Number"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow