【发布时间】:2017-12-13 22:58:10
【问题描述】:
上下文:
有 2 个主要类看起来像这样:
public class Source
{
public Dictionary<AttributeType, object> Attributes { get; set; }
}
public class Target
{
public string Title { get; set; }
public string Description { get; set; }
public List<Attribute> Attributes { get; set; }
}
以及子/集合/枚举类型:
public class Attribute
{
public string Name { get; set; }
public string Value { get; set; }
}
public enum AttributeType
{
Title,
Description,
SomethingElse,
Foobar
}
目前我的地图如下所示:
CreateMap<Source, Target>()
.ForMember(dest => dest.Description, opt => opt.MapAttribute(AttributeType.Description))
.ForMember(dest => dest.Title, opt => opt.MapAttribute(AttributeType.Title));
MapAttribute 从Dictionary 获取项目并使用我提供的AttributeType 将其作为(名称和值)对象添加到目标集合中(使用尝试获取并返回空的 if密钥不存在)...
在这一切之后,我的目标集最终看起来像这样:
{
title: "Foo",
attributes: [
{ name: "SomethingElse", value: "Bar" },
{ name: "Title", value: "Foo"}
]
}
问题:
如何将其余项目映射到目标类,但我需要能够排除特定键(如标题或描述)。例如。在 target 中具有已定义位置的 Source.Attribute 项会从 Target.Attributes 集合中排除,“剩余”属性仍会转到 Target.Attributes。
为了更清楚(如果我的来源看起来像这样):
{ attributes: { title: "Foo", somethingelse: "Bar" } }
它会像这样映射到一个目标:
{ title: "Foo", attributes: [{ name: "SomethingElse", value: "Bar" }] }
我已经尝试过了,但它没有编译,说明如下:
成员的自定义配置仅支持类型上的顶级个人成员。
CreateMap<KeyValuePair<AttributeType, object>, Attribute>()
.ForSourceMember(x => x.Key == AttributeType.CompanyName, y => y.Ignore())
【问题讨论】:
标签: c# enums automapper