Vinicius Ottoni
Vinicius Ottoni

Reputation: 4677

Is it possible access a property (by name) from a generic entity using reflection?

I would like to create a generic query from a generic class T. Is there a way to to something like that 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();
    }
}

Upvotes: 4

Views: 158

Answers (1)

jason
jason

Reputation: 241641

Make SelectBy take an 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

for example.

Upvotes: 3

Related Questions