问题
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:
protected void Application_Start()
{
Mapper.Initialize(cfg => {});
}
Code
var viewModel = Mapper.Map<MyViewModel>(formData.ToDictionary(x => x.FieldName, x => (object) x.FieldValue))
Note I'm using automapper 5.0.2.
回答1:
It works for me with the latest. Upgrade :)
来源:https://stackoverflow.com/questions/46234697/automapper-dictionary-to-object-mapping-not-working