自动映射 - 字典到对象映射不起作用?

时间:2017-09-15 08:05:25

标签: c# .net dictionary automapper

我正在尝试将字典转换为对象。我尝试过以下但它不起作用:

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 => {});
}

代码

var viewModel = Mapper.Map<MyViewModel>(formData.ToDictionary(x => x.FieldName, x => (object) x.FieldValue))

注意我正在使用automapper 5.0.2。

1 个答案:

答案 0 :(得分:1)

最新款适用于我。升级:)