Dictionary map to an object using Automapper

前端 未结 6 551
执笔经年
执笔经年 2020-11-29 07:50

Below code is just for this question

I am having a class like

public User class
{
 public string Name{get;set;}
 public string Age{get;set;
}
         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 08:09

    This thread is a bit old, but nowadays there's how to do it on automapper without any configuration, as stated at official documentation:

    AutoMapper can map to/from dynamic objects without any explicit configuration (...) Similarly you can map straight from Dictionary to objects, AutoMapper will line up the keys with property names.

    Update:

    The following code shows a working sample (with unit tests).

    void Test()
    {
        var mapper = new MapperConfiguration(cfg => { }).CreateMapper();
        var dictionary = new Dictionary()
        {
            { "Id", 1 },
            { "Description", "test" }
        };
    
        var product = mapper.Map(dictionary);
    
        Assert.IsNotNull(product);
        Assert.AreEqual(product.Id, 1);
        Assert.AreEqual(product.Description, "test");
    }
    
    class Product
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }
    

提交回复
热议问题