Is it possible to access a property (by name) from a common object using reflection?

I would like to create a general query from a general class T. Is there a way to do something like this using reflection or something else?

public class DAO<T> where T : class { protected ObjectSet<T> Entities { get { return myContextThatIsInSomewhere.CreateObjectSet<T>(); } } public IList<T> SelectBy(object fields) { if (fields == null) { throw new ArgumentNullException("fields"); } var query = from e in this.Entities select e; foreach (var field in fields.GetType().GetFields()) { query = from e in this.Entities // Do something like that: where e.(field.Name) == field.GetValue() select e; } return query.ToList(); } } 
+4
source share
1 answer

Make SelectBy take Expression<Func<T, bool>> (call it predicate ) and then you can just say

 var query = this.Entities.Where(predicate); 

You can pass an instance of Expression<Func<T, bool>> by saying

 x => x.Foo == foo 

eg.

+3
source

Source: https://habr.com/ru/post/1392699/


All Articles