【问题标题】:How do I convert a list of objects to a list of integers using AutoMapper?如何使用 AutoMapper 将对象列表转换为整数列表?
【发布时间】:2011-04-14 23:35:59
【问题描述】:

我有一个Student 对象:

public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

还有一个Classroom 对象:

public class Classroom
{
    public List<Student> Students { get; set; }
}

我想使用 AutoMapper 将学生列表转换为学生 ID 列表:

public class ClassroomDTO
{
    public List<int> StudentIds { get; set; }
}

如何配置 AutoMapper 来进行这种转换?

答案:

为了扩展我的问题和吉米的回答,这就是我最终要做的:

Mapper.CreateMap<Student, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Classroom, ClassroomDTO>()
      .ForMember(x => x.StudentIds, y => y.MapFrom(z => z.Students));

AutoMapper 足够聪明,可以完成剩下的工作。

【问题讨论】:

    标签: automapper flatten


    【解决方案1】:

    您需要一个自定义类型转换器:

    Mapper.CreateMap<Student, int>().ConvertUsing(src => src.Id);
    

    【讨论】:

    • 我不认为我可以配置某种约定,以便它始终将引用类型集合映射到整数集合?
    • 更多细节在这里:automapper.codeplex.com/…
    猜你喜欢
    • 2021-08-08
    • 2019-08-04
    • 1970-01-01
    • 2021-10-12
    • 2016-12-16
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多