【问题标题】:AutoMapper - Use method to update IEnumerable property with no setter?AutoMapper - 使用方法来更新没有设置器的 IEnumerable 属性?
【发布时间】:2017-10-18 22:38:53
【问题描述】:

我在使用 AutoMapper 从数据传输对象映射到数据库实体模型时遇到了一些问题。该实体有一些属性是自定义数组类型,派生自 IEnumerable。这些属性没有设置器,但有一个名为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&lt;String&gt; 转换为string Value 所需的SetFromString 方法?
  • 为简单起见,假设字符串需要用逗号分隔。为此,我的代码看起来像这样string.Join(",", src.CustomerNumbers);。我缺少的部分是如何将该值传递给dest.CustomerNumbers.SetFromString();

标签: c# automapper


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多