Tworzenie Expression za pomocą refleksji

0

Mam taki kod.

 if (name == nameof(Foo.Id))
                items = Get(_db.Items, m => m.);

            else if (name == nameof(Foo.Email))
                items = Get(_db.Items, m => m.Email);

            else if (name == nameof(Foo.City))
                items = Get(_db.Items, m => m.City);

            else if (name == nameof(Foo.Country))
                items = Get(_db.Items, m => m.Country);

name jest stringiem. Funkcja Get jako drugi parametr przyjmuje obiekt typu Expression który jest wejściem do funkcji IQueryable.OrderBy (wewnątrz Get()). Czy da radę uprościć ten kod wykorzystując mechanizm refleksji? Dla każdego przypadku name (Id, Email, City, Country...) muszę pisać niemal identyczny kod. Próbowałem coś takiego ale otrzymuję błąd:

 
items = Get(_db.Items, m => m.GetType().GetProperty(columnName));

Błąd: "LINQ to Entities does not recognize the method 'System.Reflection.PropertyInfo GetProperty(System.String)' method, and this method cannot be translated into a store expression."

1

Spróbuj coś takiego:

var objectParam = Expression.Parameter(typeof(TType), "x");
var property = Expression.Property(objectParam, propertyName);
var convert = Expression.Convert(property, typeof(object));
var expression = Expression.Lambda<Func<TType, object>>(convert, new ParameterExpression[] { objectParam });
 

1 użytkowników online, w tym zalogowanych: 0, gości: 1