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

时间:2015-06-04 08:21:12

标签: c# string field concatenation automapper

我花了几天的时间试图追踪这一点而没有任何运气。

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

e.g。 地址表包含: -                             地址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;

    }

由于

史蒂夫

2 个答案:

答案 0 :(得分:1)

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

我认为它已经转换了,你只是错过了实际映射源实体的代码并将结果显示给监视器,如下所示:

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

答案 1 :(得分:0)

要修改此更改,请将配置文件定义更改为:

$new()

然后在调用automapper gubbins的代码中,你需要这样做:

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

    }
}

结果现在可以保存正确的数据。

非常感谢你的帮助。