按ID获取项目并使用automapper将其标题映射到字符串

时间:2017-12-28 17:35:21

标签: c# asp.net asp.net-core automapper

我有2个型号:

public class Client
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    ...

    [ForeignKey("CountryId")]
    public Country Country { get; set; }
    public Guid CountryId { get; set; }
}

public class Country
{
    public Guid Id { get; set; }
    public string Title { get; set; }
}

我希望显示此VM:

public class ClientDetailsDto
{
    public Guid Id { get; set; }

    ...

    public string Country { get; set; } // Country's title
}

我应该如何获取Country并将其映射到ClientDetailsDto中的字符串Country?

我在我的Startup类(Startup.cs)中使用AutoMapper:

AutoMapper.Mapper.Initialize(config =>
{
    config.CreateMap<Entities.Client, Models.ClientDetailsDto>()
        .ForMember(dest => dest.Name, opt => opt.MapFrom(src =>
            $"{src.LastName} {src.FirstName} {src.Patronym}"))
        .ForMember(dest => dest.Age, opt => opt.MapFrom(src =>
            src.Birthdate.GetCurrentAge()))
        // How to get Country's title and map it to ClientDetailsDto.Country?
}

1 个答案:

答案 0 :(得分:1)

试试这个;

.ForMember(dest => dest.Country, opt => opt.MapFrom(src =>
 src.Country.Title)

完整的地图看起来像;

config.CreateMap<Entities.Client, Models.ClientDetailsDto>()
    .ForMember(dest => dest.Name, opt => opt.MapFrom(src =>
        $"{src.LastName} {src.FirstName} {src.Patronym}"))
    .ForMember(dest => dest.Age, opt => opt.MapFrom(src =>
        src.Birthdate.GetCurrentAge()))
    .ForMember(dest => dest.Country, opt => opt.MapFrom(src =>
        src.Country.Title));