Search code examples
.netlinqentity-frameworkiqueryabledto

Call a DTO translator inside IQueryable's Select


I have the following code to query an EntityContext (through a repository) and map it unto a DTO:

public class QueryQuestionsConsumer : IConsumerOf<QueryQuestionsRequest>
{
    public void Consume(QueryQuestionsRequest request)
    {
        var repo = IoC.Resolve<IUnitOfWork>().CreateRepository<Question>();
        var filter = FilterTranslator.CreateFilterExpression<Question>(request.Filters);
        var questions = repo
            .GetAll()
            .Where(filter)

        Result = questions.Select(question => QuestionTranslator.ToDTO(question)).ToArray()
    }

}

This would obviously fail because ToDTO() isn't a recognized function in EntityFramework provider. I could create a DTO object using an object initializer but I'd like to delegate it to another class (QuestionTranslator).

What do you do in this case?

UPDATED: Additionally, I don't want to hydrate a full Question Object to do that. I'd like to count on Provider's ability to create DTO objects.


Solution

  • Besides the obvious option of using questions.AsEnumerable().Select(...) to force EF to retrieve full records and then mapping them client side, you can make your ToDTO method return an expression:

    Expression<Func<Question, QuestionDTO>> ToDTO()
    {
        Expression<Func<Question, QuestionDTO>> exp =
            question => new QuestionDTO { ... };
        return exp;
    }