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

标签 c# automapper

我在使用 AutoMapper 从数据传输对象映射到数据库实体模型时遇到了一些问题。该实体有一些属性是自定义数组类型,派生自 IEnumerable。这些属性没有 setter ,但有一个名为 SetFromString() 的方法可用。我似乎无法正确配置我的 map 来使用它。 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));
    }
}

再次感谢您提供的任何帮助!

最佳答案

您可以为目标实体 CustomerNumbers 成员使用 UseDestinationValueIgnore 并在 AfterMap 中执行实际映射:

cfg.CreateMap<ContactDto, ContactEntity>()
    .ForMember(dest => dest.CustomerNumbers, opt => opt.Ignore())
    .AfterMap((src, dest) => dest.CustomerNumbers.SetFromString(string.Join(",", src.CustomerNumbers)));

关于c# - AutoMapper - 使用方法更新没有 setter 的 IEnumerable 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46811703/

相关文章:

c# - RsaSecurityKey 不将 RSAParameters 作为参数

c# - 如何配置 AutoMapper 在映射时不检查成员列表?

c# - EF 4.4 不检测 AutoMapper 所做的更改

C# AutoMapper,如何映射组数

c# - 使用带有泛型类的 ContextBuilder 使用 Entity Framework 4 创建 EDMX/DB-Schema 的异常

c# - 使用 LINQ 查询获取索引值的集合

javascript - 无法加载资源: the server responded with a status of 500 (Internal Server Error) while returning image in base64 format from controller

c# - App.config 问题与同一解决方案中的许多项目

asp.net-mvc - 将 DTO 绑定(bind)到域模型的位置

c# - 缺少类型映射配置或不支持的映射