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



我花了几天时间试图追踪这个,但没有任何运气。

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

。地址表中包含:-Address1 =门牌号Address2 =街道Address3 =Address4 = Town

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

按要求,这是我在哪里:-

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); 

要解决这个问题,请将Profile Definition更改为:

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

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

var query = from a in addressRepository.GetAll() select a;
IList<AddressSearchResponseDto> result = Mapper.Map<IList<Address>, IList<AddressSearchResponseDto>>(query.ToList());

result现在保存了正确的数据。

非常感谢你们的帮助。

相关内容

  • 没有找到相关文章

最新更新