2011-08-16 55 views
0

说我有以下定义一个类的属性:映射枚举类具有相同枚举类型

public class DestinationOuter 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public List<DestinationInner> Siblings { get; set; } 
} 

public class DestinationInner 
{ 
    public string Name { get; set; } 
    public RelationEnum Relation { get; set; } 
} 

而且说我有一个源类型:

public class SourceSiblings 
{ 
    public string Name { get; set; } 
    public RelationEnum Relation { get; set; } 
} 

随着AutoMapper我可以很容易地创建一个配置,从SourceSiblingsDestinationInner的映射,让我来做这样的映射:

SourceSiblings[] brothers = { ... }; 
DestinationOuter dest = new DestinationOuter(); 

Mapper.Map(brothers, dest.Siblings); 

但我想要做的是直接从SourceSiblingsDestinationOuter。在这种情况下,DestinationOuter中的名称和年龄属性在映射中将被忽略,但想法是SourceSiblings将映射到DestinationOuter.Siblings。使用上面的对象声明,我希望能够做到:

Mapper.Map(brothers, dest); 

我不知道如何让这个工作。我可以设置的配置,像这样:

CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>(); 

但是,这并不做任何事情。好像我需要能够这样说:

CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>() 
     .ForMember(dest => dest.Siblings, 
        opt => opt.MapFrom(src => src)); 

虽然上面的编译,Mapper.Map实际上并不映射值。

回答

1

此代码似乎适用于我,但它几乎是你所说的没有做任何事情。

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     SourceSiblings[] brothers = { 
             new SourceSiblings {Name = "A", Relation = 1}, 
             new SourceSiblings {Name = "B", Relation = 2} 
            }; 
     var dest = new DestinationOuter(); 

     Mapper.CreateMap<SourceSiblings, DestinationInner>(); 

     Mapper.CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>() 
      .ForMember(d => d.Name, opt => opt.Ignore()) 
      .ForMember(d => d.Age, opt => opt.Ignore()) 
      .ForMember(d => d.Siblings, opt => opt.MapFrom(s => s)); 

     Mapper.Map(brothers, dest); 
     Console.Write(dest.Siblings.Count); 
     Console.ReadLine(); 
    } 
} 

public class DestinationOuter 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public List<DestinationInner> Siblings { get; set; } 
} 

public class DestinationInner 
{ 
    public string Name { get; set; } 
    public int Relation { get; set; } 
} 

public class SourceSiblings 
{ 
    public string Name { get; set; } 
    public int Relation { get; set; } 
} 
+0

只是为了确认,你是在'Mapper.Map'调用后说'dest.Siblings'不包含任何记录,对吧? –

+0

不,相反。 dest.Siblings完全填充。 – boca

+0

Arg,现在适用于我......我的问题是在'DestinationOuter'中,我有'Siblings'列表作为只读属性。 URG。感谢您的帮助,并花时间表明我的理论是完善的,它应该起作用。 –