【发布时间】:2015-08-18 18:06:42
【问题描述】:
我花了几天时间试图找到这个,但没有任何运气。
我有一个地址表。每行有 4 个地址字段。我想将它们映射到另一个对象,该对象具有一个字段,该字段是由 4 个字段组成的单个字符串,但是(总是有一个但是),如果其中一个字段包含 null 或空字符串,我想忽略它。
例如 地址表包含:- 地址 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;
}
谢谢
史蒂夫
【问题讨论】:
-
请提供任何代码示例
-
感谢您的快速回复。我已经用代码更新了问题
标签: c# string field concatenation automapper