Vijay Ganesh
Vijay Ganesh

Reputation: 265

Passing lambda expressions as parameters using reflection

I have a generic repository method call which is as follows

var result = Repository<MyDbClass>.Get(x => x.MyProperty1 == "Something"
&& (!x.MyProperty2.HasValue || x.MyProperty2 == "SomethingElse"));

I hope to call this method using reflection. I am mainly looking for a way to pass the lambda expression as a parameter using reflection.

EDIT

Actually my repository type will be known only at runtime. The tables under all these repositories are similar having some columns in common. It is on these columns the filter is applied. So I cannot pass an expression as it is.

public void SomeMethod<T, TR>(T repository, TR dataObject)
{
    var type = repository.GetType();
    var dataType = dataObject.GetType();
    var getMethod = type.GetMethod("Get");
    //How to invoke the method by passing the lambda as parameter(??)

}

Upvotes: 2

Views: 2189

Answers (1)

Jan P.
Jan P.

Reputation: 3297

Try passing a Func<TR, bool>

var method = typeof(TR).GetMethod("Get");

if (method != null)
{
    method.Invoke(new Func<TR, bool>(
        (x) => x.MyProperty1 == "Something" /* etc... */));
}

By assuming you use LINQ methods in your Get method, you can just fill the func in like this

public IEnumerable<TR> Get<TR>(Func<TR, bool> func)
{
    return
        db.MyDbClassEntities.Where(func);
}

Upvotes: 1

Related Questions