本文介绍了Automapper-字典到对象映射不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将字典转换为对象.我尝试了以下方法,但没有用:
I'm trying to convert a dictionary to an object. I've tried the following but it doesnt work:
public class FormField
{
public string FieldName { get; set;}
public string FieldValue { get; set;}
}
var formData = new List<FormField>
{
new FormField {FieldName = "date", FieldValue = "2017-09-14"},
new FormField {FieldName = "name", FieldValue = "Job blogs"},
new FormField {FieldName = "isenabled", FieldValue = "true"}
};
public class MyViewModel
{
[Required]
public DateTime Date { get; set; } = DateTime.now;
[Required]
public string Name { get; set; }
public boolean IsEnabled { get; set; }
public IEnumerable<SelectListItem> Titles
{
get
{
var options = new List<SelectListItem>
{
new SelectListItem(){ Value = "Mr", Text = "Mr" },
new SelectListItem(){ Value = "Mrs", Text = "Mrs" }
};
return options;
}
}
}
Global.asax:
Global.asax:
protected void Application_Start()
{
Mapper.Initialize(cfg => {});
}
代码
var viewModel = Mapper.Map<MyViewModel>(formData.ToDictionary(x => x.FieldName, x => (object) x.FieldValue))
注意,我正在使用automapper 5.0.2.
Note I'm using automapper 5.0.2.
推荐答案
最新的版本对我有效.升级:)
It works for me with the latest. Upgrade :)
这篇关于Automapper-字典到对象映射不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!