c# - AutoMapper项目To : Not working with nested objects

标签 c# linq automapper

我有以下 dto:

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

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

然后我尝试使用 AutoMapper 映射它,如下所示:

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));

然后我使用 ProjectTo:

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

但是,当我执行查询时,我的过滤器集合为空。

当我尝试使用 LINQ 手动映射集合时,如下所示,它工作正常,所以我想知道我是否做错了什么?

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

最佳答案

一般来说,我认为最好避免在配置文件配置中调用 Mapper.Map() 。考虑到这一点,我认为将您的第一个映射更改为以下内容可能会有所帮助:

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

关于c# - AutoMapper项目To : Not working with nested objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46905879/

相关文章:

c# - 访问静态数据的设计模式

c# - 在 gridview 中使用 OnSelectChange 打印到标签

c# - TPL Dataflow SingleProducerConstrained 是指源 block 的数量还是它们的并行度?

c# - 将 hashtable.Keys 转换为 List<int> 或其他 IEnumerable<int>

c# - 在 LINQ 中有条件地加入

c# - 在 C# 中,如何按对象的多个字段对对象集合进行排序?

c# - 这是 AutoMapper 2.0.0 和 2.2.0 之间的重大变化吗?

c# - 在 LINQ 中筛选 ProjectToList

c# - 如何使 LINQ 表达式返回到类中?

c# - ASP.NET MVC 多层应用程序 : where to place Automapper initialization?