2016-05-14 59 views
1

如何忽略目標中缺少的屬性? 現在我的代碼是Automapper:忽略目標中缺少的屬性

public class UISource 
{ 
    public string Field1 { get; set; } 
    public string Field2 { get; set; } 
} 
public class DBTarget 
{ 
    public string Field1 { get; set; } 
    public string Field2 { get; set; } 
    public string Field3 { get; set; } 
    public string Field4 { get; set; } 
}  
public static class Helper 
{ 
    public static D Map<S, D>(S uiSource) where D : class, new() 
    { 
     MapperConfiguration config = new MapperConfiguration(cfg => 
     { 
      cfg.CreateMap<S, D>(); 
     }); 
     IMapper mapper = config.CreateMapper(); 
     D destination = mapper.Map<S, D>(uiSource); 
     return destination; 
    } 
} 
    private void SomeMethod() 
    { 
     UISource uiSource = new UISource(); 
     uiSource.Field1 = "NewValue1"; 
     uiSource.Field2 = "NewValue2"; 

     DBTarget dbTarget = new DBTarget(); 
     dbTarget.Field1 = "OldValue1"; 
     dbTarget.Field2 = "OldValue2"; 
     dbTarget.Field3 = "SomeOtherValue"; 
     dbTarget.Field4 = "SomeOtherValue"; 

     dbTarget = Helper.Map<UISource, DBTarget>(uiSource); 
    } 

此代碼dbTarget.Field3和dbTarget.Field4空。我正在使用Automapper 4.2.1。 我已嘗試This,但它不能在最新版本中工作...

回答

0

Map方法已重載,因此您可以提供目標以及源。重構輔助類接受d的目標是這樣的:

public static D Map<S, D>(S uiSource, D dbTarget) where D : class, new() 
    { 
     MapperConfiguration config = new MapperConfiguration(
      cfg => 
       { cfg.CreateMap<S, D>(); }); 

     IMapper mapper = config.CreateMapper(); 

     D destination = mapper.Map<S, D>(uiSource, dbTarget); 

     return destination; 
    } 

你可以調用助手這樣的:

dbTarget = Helper.Map<UISource, DBTarget>(uiSource, dbTarget); 

字段3和字段4的值映射後堅持!