5

I have the following dto:

public class SingleForm
{
    // other props left out for brevity

    public List<Filter> Filters { get; set; }
}

I then try mapping it with AutoMapper like so:

CreateMap<Form, SingleForm>()
    .ForMember(dest => dest.Filters, 
        opts => opts.MapFrom(src => 
            Mapper.Map<List<Filter>>(src.Questions)));

CreateMap<FormQuestion, Filter>()
    .ForMember(dest => dest.Header, 
        opts => opts.MapFrom(src => src.Question.QuestionText));

I then use ProjectTo:

var query = this.context.Forms
    .Where(e => e.Id == message.FormId)
    .ProjectTo<SingleForm>()
    .FirstOrDefault();

However, my filters collection is empty when I execute the query.

When I try to manually map the collection using LINQ, like below, it works correctly, so I'm wondering if I am doing something wrong?

var query = this.context.Forms
    .Where(e => e.Id == message.FormId)
    .Select(e => new SingleForm
    {
        Id = e.Id,
        Filters = e.Questions.Select(q =>
            new Filter { 
                Header = q.Question.QuestionText 
        }).ToList()
    })
    .FirstOrDefault();

2 Answers 2

3

In general, I think it is best to avoid calling Mapper.Map() within your profile configuration. With this in mind, I think changing your first mapping to the following may help:

CreateMap<Form, SingleForm>()
    .ForMember(dest => dest.Filters,
        opts => opts.MapFrom(src => src.Questions));
Sign up to request clarification or add additional context in comments.

Comments

0

If the mapping happens out side DbContext then should using includes method to retrieve all relationships items which nit able to lazy load without DbContext.

1 Comment

That's kind of the point of ProjectTo() - see Automapper Queryable Extensions

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.