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
Compileon the expression.