2011-08-16 186 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。感謝您的幫助,並花時間表明我的理論是完善的,它應該起作用。 –