AutoMapper - 使用方法更新没有setter的IEnumerable属性?

3
我在使用AutoMapper将数据传输对象映射到数据库实体模型时遇到了些问题。该实体具有一些自定义的数组类型属性,派生自IEnumerable,并且这些属性没有setter,但有一个名为SetFromString()的方法可用。我无法正确配置我的映射来使用它。AutoMapper支持这种操作吗?如果有人能指点我正确的方向,我将不胜感激。
以下是我正在处理的关键类的缩减版本。(从实体到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));
    }
}

感谢您能提供的任何帮助!

如果您手动进行操作,您会如何将 List<String> 转换为 SetFromString 方法所需的 string Value - Ivan Stoev
为了简单起见,假设字符串需要用逗号分隔。因此,我的代码看起来像这样 string.Join(",", src.CustomerNumbers);。我缺少的部分是如何将该值传递给 dest.CustomerNumbers.SetFromString(); - wags
1个回答

4
您可以在目标实体的CustomerNumbers成员中使用 UseDestinationValueIgnore,然后在AfterMap中执行实际映射:
cfg.CreateMap<ContactDto, ContactEntity>()
    .ForMember(dest => dest.CustomerNumbers, opt => opt.Ignore())
    .AfterMap((src, dest) => dest.CustomerNumbers.SetFromString(string.Join(",", src.CustomerNumbers)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接