简体   繁体   中英

How do I convert an Expression to a lambda expression?

I am trying to convert an Expression of type Expression<Func<Entity, bool>> to a Func<Entity, bool> .

The background here is that I am trying to mock a repository so that it will return one of a collection of mock entities for a given key value. (I could hard code the input values to the mocked method but this seems like the wrong approach for a large number of items).

So I am trying to mock the First method on my repository like this:

var collection = new List<Entity> 
{ 
    mockedEntity1, 
    mockedEntity2, 
    mockedEntity3, 
    ... 
};

mockRepository
    .Setup(rep => rep.First(It.IsAny<Expression<Func<Entity, bool>>>()))
    .Returns<Expression<Func<Entity, bool>>>(e => collection.First(e));

This doesn't work because collection.First takes a Func rather than an Expression>. So I have got to the point where I need to convert the Expression to the Func that it contains.

Perhaps there a simpler or better to do this?

You need to call Compile on the expression.

It already is a lambda expression. But to get a delegate from the lambda, call .Compile() .

In the general sense - to make a lambda from an Expression you would use Expression.Lambda, indicating the desired type and including the parameter (declaration) instances (from Expression.Parameter). However, this is not required here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM