2

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(??)

}
1

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

7 Comments

I will know my repository type only at runtime. Question edited for more clarity.
Can I really form an expression like that without the compiler knowing what TR is? What is the relation between MyProperty1 and TR?
You can't archive what you want if the compile hasn't any information about the TR type. Isn't there any interface implemented by the possible types?
can't I build an expression tree using TR as I do know the properties in TR used in the expression?
You could do this, but it would be very dangerous if an unexpected type is passed to the function. Do you know all types that may be passed to the function?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.