2016-10-03 74 views
0

在目標類的副本是否有辦法讓整個源對象在我的目的地類作爲一個屬性的副本..飼養來源,使用Automapper

例如

來源:

class SourceClass 
{ 
    prop string Prop1 { get; set; } 
    prop string Prop2 { get; set; } 
} 

目的地:

class DestinationClass 
{ 
    prop string Prop1 { get; set; } 
    prop string Prop2 { get; set; } 
    prop SourceClass SourceClassCopy { get; set; } 
} 

,並使用automapper配置類似

AutoMapper.Mapper.Initialize(cfg => { 
     cfg.ReplaceMemberName("this", "SourceClassCopy"); 
     cfg.CreateMap<SourceClass, DestinationClass>(); //or .ForMember("SourceClassCopy", d => d.MapFrom(s => s)); 
    }); 

爲什麼我這樣做是怎麼把我有一個分層對象,並會喜歡爲反向映射保留副本,因爲Source類沒有默認構造或者這將幫助我扭轉地圖。另外,源類是,我不能修改:(和有方法/接受整個源對象的函數庫感謝所有幫助謝謝

回答

0

你可以這樣說:。

public class SourceClass 
{ 
    public string Prop1 { get; set; } 
    public string Prop2 { get; set; } 
} 

public class DestinationClass 
{ 
    public string Prop1 { get; set; } 
    public string Prop2 { get; set; } 
    public SourceClass SourceClassCopy { get; set; } 
} 

public class Program 
{ 
    public void Main() 
    { 
     var source = new SourceClass(); 
     source.Prop1 = "Prop1Source"; 
     source.Prop2 = "Prop2Source"; 

     var destination = new DestinationClass(); 
     destination.Prop1 = "Prop1Dest"; 
     destination.Prop2 = "Prop2Dest"; 

     var sourceinDest = new SourceClass(); 
     sourceinDest.Prop1 = "Prop1sourceinDest"; 
     sourceinDest.Prop2 = "Prop2sourceinDest"; 
     destination.SourceClassCopy = sourceinDest; 

     // Configure AutoMapper 
     Mapper.CreateMap<SourceClass, DestinationClass>() 
      .ForMember(dest => dest.SourceClassCopy, m=>m.MapFrom(src=>src)); 

     Mapper.Map<SourceClass, DestinationClass>(source, destination); 


     Console.WriteLine(destination.Prop1); 
     Console.WriteLine(destination.Prop2); 
     Console.WriteLine(destination.SourceClassCopy.Prop1);  
     Console.WriteLine(destination.SourceClassCopy.Prop2);  
    } 
} 
+0

是的,這工作..謝謝 – narcs