2016-08-01 69 views
3

我有下面的代碼已經在Automapper的v3中工作,但不再在v5中。 更新它也適用於v4。Automapper v5升級後的空屬性值

CallScheduleProfile在其構造函數中將Title屬性設置爲類的實例,該實例將值true傳遞給它。

CallScheduleProfileViewModel在其構造設置一個Title屬性到該傳遞的true"Title"的值的不同的類的實例。

我已經在AutoMapper中爲所有4個類設置了映射,然後我調用Map。

的結果是,該地圖後Title財產上CallScheduleProfileViewModeltrue一個布爾值,但FriendlyName是空的,即使它在它的構造函數的設定。

我認爲正在發生的事情是,在CallScheduleProfileViewModel構造函數被調用,FriendlyName被越來越賦予但是當映射發生時呼籲Entry的構造函數,然後任何屬性映射上UxEntry存在,並指定該到​​Title財產和默認FriendlyName將爲空,因爲FriendlyName不存在UxEntry它的值不被複制。

我可能在這個假設中是錯誤的,但是無論哪種方式,我如何在映射上填充FriendlyName

更新:我查看了嵌套類型的Automapper documentation,問題也存在於文檔中提供的代碼中。如果我將一個字符串屬性添加到InnerDest並將其值設置爲OuterDest的構造函數,則Map之後其值爲空。

A)構造Entry<T>類型此屬性設置爲null

B)Automapper後產生的Entry<T>一個新實例():

public static void Main(string[] args) 
{ 
    Mapper.Initialize(cfg => 
    { 
     cfg.CreateMap<UxEntry<bool>, Entry<bool>>(); 

     cfg.CreateMap<CallScheduleProfile, CallScheduleProfileViewModel>(); 
    }); 

    var old = new CallScheduleProfile(); 

    var newmodel = Mapper.Map<CallScheduleProfile, CallScheduleProfileViewModel>(old); 

    Console.WriteLine(newmodel.Title.Value); 
    Console.WriteLine(newmodel.Title.FriendlyName); 
} 

public class UxEntry<T> 
{ 
    public static implicit operator T(UxEntry<T> o) 
    { 
     return o.Value; 
    } 

    public UxEntry() 
    { 
     this.Value = default(T); 
    } 

    public UxEntry(T value) 
    { 
     this.Value = value; 
    } 

    public T Value { get; set; } 
} 


public class CallScheduleProfile 
{ 
    public CallScheduleProfile() 
    { 
     this.Title = new UxEntry<bool>(true); 
    } 

    public UxEntry<bool> Title { get; set; } 

} 

public class Entry<T> 
{ 
    public Entry() 
    { 
    } 

    public Entry(T value, string friendlyName) 
    { 
     this.Value = value; 
     this.FriendlyName = friendlyName; 
    } 

    public T Value { get; set; } 
    public string FriendlyName { get; set; } 

    public static implicit operator T(Entry<T> o) 
    { 
     return o.Value; 
    } 
} 


public class CallScheduleProfileViewModel 
{ 
    public CallScheduleProfileViewModel() 

    { 
     this.Title = new Entry<bool>(true, "Title"); 
    } 
    public Entry<bool> Title { get; set; } 
} 

回答

0

好,Automapper因爲這個屬性null地圖!調用CallScheduleProfileViewModel中的構造函數。

C)有用於Automapper

沒有設定其他規則

什麼,你可以在這裏做的是改變配置,讓你讓Automapper知道應該使用的一個屬性的默認值:

 Mapper.Initialize(cfg => 
     { 
      // when UxEntry is mapped to Entry value "Title" is used for property FriendlyName 
      cfg.CreateMap<UxEntry<bool>, Entry<bool>>() 
       .ForMember(dest => dest.FriendlyName, opt => opt.UseValue("Title")); 

      cfg.CreateMap<CallScheduleProfile, CallScheduleProfileViewModel>(); 
     }); 

現在我們可以從CallScheduleProfileViewModel的構造函數中刪除多餘的屬性初始化。

沒有其他的變化運行你的代碼將產生以下輸出:

true  
Title 
+0

我居然發現'CFG。CreateMap ()。ForMember(dest => dest.Title,o => o.UseDestinationValue());'也工作 – Jon

+0

@Jon Wow,那很好... – Fabjan