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

问题描述 投票:1回答:1

我有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并将其映射到客户端详细信息中的字符串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?
}
c# asp.net asp.net-core automapper
1个回答
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));
© www.soinside.com 2019 - 2024. All rights reserved.