使用 Automapper 将单独的字段映射到一个字符串中

Mapping separate fields into one string using Automapper

我花了几天时间试图找到它,但没有任何运气。

我有 table 个地址。每行有 4 个地址字段。我想将它们映射到另一个对象,该对象有一个字段,该字段是由 4 个字段组成的单个字符串,但是(总是有一个但是),如果其中一个字段包含 null 或空字符串,我想忽略它。

例如 地址 table 包含:- 地址 1 = 门牌号 地址 2 = 街道 地址3 = 地址 4 = 城镇

新对象将包含字符串 :- 门牌号、街道、城镇。

根据要求,这是我所在的位置:-

AutoMapper 配置文件

public static class AutoMapperConfig
{
    public static void Configure()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile(new AddressSearchList_ToResponse_Profile());
        });
    }
}

配置文件定义:

    public class AddressSearchList_ToResponse_Profile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<Address, AddressSearchResponseDto>()
            .ConvertUsing<ConvertAddressToSearchList>();

        Mapper.AssertConfigurationIsValid();

        //This is as far as I get - what am I missing

    }
}

最后是转换例程(诚然这不是有史以来最流畅的代码):

public class ConvertAddressToSearchList : ITypeConverter<Address, AddressSearchResponseDto>
{

    public AddressSearchResponseDto Convert(ResolutionContext context)
    {

        string newAddress = string.Empty;
        Address oldAddress = (Address)context.SourceValue;
        int addressId = oldAddress.Id;

        newAddress = oldAddress.AddressLine1;

        if (!String.IsNullOrEmpty(oldAddress.AddressLine2))
        {
            newAddress += ", " + oldAddress.AddressLine2;
        }

        if (!String.IsNullOrEmpty(oldAddress.AddressLine3))
        {
            newAddress += ", " + oldAddress.AddressLine3;
        }

        if (!String.IsNullOrEmpty(oldAddress.AddressLine4))
        {
            newAddress += ", " + oldAddress.AddressLine4;
        }

        if (!String.IsNullOrEmpty(oldAddress.County))
        {
            newAddress += ", " + oldAddress.County;
        }

        if (!String.IsNullOrEmpty(oldAddress.Postcode))
        {
            newAddress += ".  " + oldAddress.Postcode;
        }


        AddressSearchResponseDto searchAddress = new AddressSearchResponseDto { Id = addressId, Address = newAddress };

        return searchAddress;

    }

谢谢

史蒂夫

也许,只有我,但是(总有一个但是),问题是什么?

我认为它已经转换了,您只是缺少实际映射源实体并显示要监视的结果的代码,如下所示:

AddressSearchResponseDto result = Mapper.Map<Address,AddressSearchResponseDto>(source); 
Console.WriteLine(result.newAddress); 

要解决此问题,请将配置文件定义更改为:

public class AddressSearchList_ToResponse_Profile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<Address, AddressSearchResponseDto>()
            .ConvertUsing<ConvertAddressToSearchList>();

    }
}

然后在调用自动​​映射器 gubbins 的代码中,您需要这样做:

var query = from a in addressRepository.GetAll() select a;

IList<AddressSearchResponseDto> result = Mapper.Map<IList<Address>, IList<AddressSearchResponseDto>>(query.ToList());

结果现在包含正确的数据。

非常感谢你们的帮助。