AutoMapper - 使用方法来更新IEnumerable属性没有setter?
问题描述:
我在使用AutoMapper从数据传输对象映射到数据库实体模型时遇到了一些麻烦。该实体具有几个属性,这些属性是从IEnumerable派生的自定义数组类型。这些属性没有安装程序,但有一种名为SetFromString()
的方法可用。我似乎无法正确配置我的地图来使用它。 AutoMapper是否支持这种事情?如果有人能指出我的方向正确,我会很感激。AutoMapper - 使用方法来更新IEnumerable属性没有setter?
下面是我正在使用的关键类的简化版本。 (映射工作得很好,从实体到DTO去,但我需要它在相反方向上正常工作。)
// The database entity
public class ContactEntity
{
public CustomArray<String> CustomerNumbers { get; }
}
// The data transfer object
public class ContactDto
{
public List<String> CustomerNumbers { get; set; }
}
// CustomArray definition
public abstract class CustomArray<DataType> : IEnumerable<DataType>, IDisposable
{
protected CustomArray();
public abstract void SetFromString(string Value);
}
我的映射分布仍然是相当香草,因为我不能环绕我的头正确的ForMember
语法。
public class ContactMappingProfile : Profile
{
public ContactMappingProfile()
{
// This map works fine
CreateMap<ContactEntity, ContactDto>();
// Map from DTO to Entity
CreateMap<ContactDto, ContactEntity>()
.ForMember(dest => dest.CustomerNumbers,
opt => opt.ResolveUsing(src => src.CustomerNumbers));
}
}
再次感谢您提供的任何帮助!
答
你可以使用任何UseDestinationValue
或Ignore
为目标实体CustomerNumbers
成员和执行AfterMap
实际映射:
cfg.CreateMap<ContactDto, ContactEntity>()
.ForMember(dest => dest.CustomerNumbers, opt => opt.Ignore())
.AfterMap((src, dest) => dest.CustomerNumbers.SetFromString(string.Join(",", src.CustomerNumbers)));
如果你是做手工,你会如何转换列表''到'字符串Value' 'SetFromString'方法需要吗? –
为了简单起见,假设字符串需要用逗号分隔。为此,我的代码看起来像这样:'string.Join(“,”,src.CustomerNumbers);'。我遗漏的部分是如何将该值传递给'dest.CustomerNumbers.SetFromString();' – wags