2010-09-03 67 views
0

的複雜集合這裏是我有什麼,我希望有人能幫助我們:與Automapper

class Source 
{ 
    string name { get; set; } 
    Inner { get; set; } 
} 

class Inner 
{ 
    Col A { get; set; } 
    Col B { get; set; } 
} 


class Col : IList<ClassX>, IEnunmerable<ClassX> 

我需要Source類映射到具有目標類型:

class Dest 
{ 
    string name { get; set; } 
    IList<ClassY> A { get; set;} 
    IList<ClassY> B { get; set;} 
} 

現在, ClassXClassY類共享相同的屬性。 ClassY類具有ClassX基本屬性的子集,並具有完全相同的名稱和類型。

嘗試了各種映射。只是ClassXClassY地圖,與集合,不具有和具有任何映射得到沒有映射之間或缺少配置發現SourceDest

AutoMapper.Mapper.Map < SourceDest>(SRC)之間;

有人可以幫助我與映射嗎?提前致謝。

+0

澄清:你希望dest.name來自source.name和dest.A來自source.Inner.A和dest.B來自source.Inner.B? – PatrickSteele 2010-09-10 23:12:03

+0

帕特里克,是的,這是我追求的行爲。 – gsogol 2010-09-12 17:49:15

回答

0

這個問題是一個幾個月大,但如果你還在尋找一個答案,這是我試過的工作:

class Source 
{ 
    public string Name { get; set; } 
    public Inner Inner { get; set; } 
} 
class Inner 
{ 
    public Col A { get; set; } 
    public Col B { get; set; } 
} 
class Col : List<ClassX> { } 
class ClassX 
{ 
    public int Index { get; set; } 
    public string Name { get; set; } 

    public ClassX() : this(0, "") { } 
    public ClassX(int index, string name) 
    { 
     this.Index = index; 
     this.Name = name; 
    } 
} 
class ClassY 
{ 
    public int Index { get; set; } 
    public string Name { get; set; } 

    public ClassY() : this(0, "") { } 
    public ClassY(int index, string name) 
    { 
     this.Index = index; 
     this.Name = name; 
    } 
} 
class Dest 
{ 
    public string Name { get; set; } 
    public List<ClassY> A { get; set; } 
    public List<ClassY> B { get; set; } 
} 

[TestMethod] 
public void ComplexTest() 
{ 
    Mapper.CreateMap<Source, Dest>() 
     .ForMember(dest => dest.A, config => config.MapFrom(src => src.Inner.A)) 
     .ForMember(dest => dest.B, config => config.MapFrom(src => src.Inner.B)); 
    Mapper.CreateMap<ClassX, ClassY>(); 

    Source source = new Source 
     { 
      Name = "Source", 
      Inner = new Inner 
       { 
        A = new Col 
         { 
          new ClassX(1, "First"), 
          new ClassX(2, "Second"), 
          new ClassX(3, "Third"), 
          new ClassX(4, "Fourth"), 
         }, 
        B = new Col 
         { 
          new ClassX(5, "Fifth"), 
          new ClassX(6, "Sixth"), 
          new ClassX(7, "Seventh"), 
          new ClassX(8, "Eighth"), 
         }, 
       } 
     }; 

    Dest destination = Mapper.Map<Source, Dest>(source); 

    Assert.AreEqual(source.Name, destination.Name); 
    Assert.AreEqual(source.Inner.A.Count, destination.A.Count); 
    Assert.AreEqual(source.Inner.B.Count, destination.B.Count); 
    Assert.AreEqual(source.Inner.A[0].Name, destination.A[0].Name); 
    Assert.AreEqual(source.Inner.B[0].Name, destination.B[0].Name); 
} 

我沒去太深入我的斷言,所以可能有一些我錯過了,但他們似乎被正確映射。