2017-09-15 70 views
5

语境:AutoMapper:映射过程中忽略特定的单词表项(S)

那里,看起来像这样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,将其添加到目标集合为(名称&值),对象(使用尝试获取并返回一个空如果该键不存在)...

这一切我的目标设定结束的这样看后:

{ 
    title: "Foo", 
    attributes: [ 
    { name: "SomethingElse", value: "Bar" }, 
    { name: "Title", value: "Foo"} 
    ] 
} 


问:

如何将其余项目映射到目标类,但我需要能够排除特定键(如标题或描述)。例如。 Source.Attribute在Target中具有已定义位置的项目将从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()) 

回答

3

它可以在映射配置前置过滤器值,一些值将甚至不会去目标 我使用automapper V6.1。1,也有一些差别,但这个想法应该是相同的)

为了让事情的作品我要补充KeyValuePair<AttributeType, object>Attribute映射第一(MapAttribute刚刚返回字典值)

CreateMap<KeyValuePair<AttributeType, object>, Attribute>() 
    .ForMember(dest => dest.Name, opt => opt.MapFrom(s => s.Key)) 
    .ForMember(dest => dest.Value, opt => opt.MapFrom(s => s.Value)); 

,因为它的定义哪些属性应该被忽略,他们会去忽略列表,在此基础上映射将过滤掉多余的属性

var ignoreAttributes = new[] {AttributeType.Description, AttributeType.Title}; 
CreateMap<Source, Target>() 
    .ForMember(dest => dest.Description, opt => opt.MapFrom(s => s.MapAttribute(AttributeType.Description))) 
    .ForMember(dest => dest.Title, opt => opt.MapFrom(s => s.MapAttribute(AttributeType.Title))) 
    .ForMember(dest=>dest.Attributes, opt=> opt.MapFrom(s=>s.Attributes 
     .Where(x=> !ignoreAttributes.Contains(x.Key)))); 

根据最终的映射例子

var result = Mapper.Map<Target>(new Source 
{ 
    Attributes = new Dictionary<AttributeType, object> 
    { 
     {AttributeType.Description, "Description"}, 
     {AttributeType.Title, "Title"}, 
     {AttributeType.SomethingElse, "Other"}, 
    } 
}); 

结果将填补Titel的,说明,只是一个属性SomethingElse

enter image description here enter image description here