我在使用 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
成员使用 UseDestinationValue
或 Ignore
并在 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/