[英]How to map a viewModel to a hierarchy model with arrays with AutoMapper?
一個深層模型是由具有大量數組的代碼生成的(想想基於wsdl的WCF代理生成的代碼),這些數組需要用扁平化的視圖模型填充。 這兩個模型之間沒有命名約定。
平面模型看起來像這樣:
public class ViewModel
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
深度模型看起來像這樣:
public class DeepLevel0
{
public DeepLevel1 Level1 { get; set; }
}
public class DeepLevel1
{
public string Prop1;
public DeepLevel2[] Level2 { get; set; }
}
public class DeepLevel2
{
public string Prop2;
public string Prop3;
}
最終映射結果應為以下內容
DeepLevel0.Level1.Prop1 = ViewModel.Item1
DeepLevel0.Level1.Level2[0].Prop2 = ViewModel.Item2
DeepLevel0.Level1.Level2[0].Prop2 = null;
我真的很喜歡AutoMapper中的驗證系統,因為您已經處理了所有屬性。
我得到了以下工作(但失去了驗證):
Mapper.CreateMap<ViewModel, DeepLevel0>()
.ForMember(d => d.Level1, opt => opt.MapFrom(s =>
new DeepLevel1 {
Prop1 = s.Item1,
Level2 = new[]
{
new DeepLevel2
{
Prop2 = s.Item2,
Prop3 = null
}
}
}));
}
還有其他更好的方法嗎?
不,我不這么認為。 您始終可以切換到對DeepLevel對象使用構造函數,這可能會使它們整理起來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.