我有下面的代碼已經在Automapper的v3中工作,但不再在v5中。 更新它也適用於v4。Automapper v5升級後的空屬性值
CallScheduleProfile
在其構造函數中將Title
屬性設置爲類的實例,該實例將值true
傳遞給它。
CallScheduleProfileViewModel
在其構造設置一個Title
屬性到該傳遞的true
和"Title"
的值的不同的類的實例。
我已經在AutoMapper中爲所有4個類設置了映射,然後我調用Map。
的結果是,該地圖後Title
財產上CallScheduleProfileViewModel
有true
一個布爾值,但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; }
}
我居然發現'CFG。CreateMap()。ForMember(dest => dest.Title,o => o.UseDestinationValue());'也工作 –
Jon
@Jon Wow,那很好... – Fabjan