使用automapper

时间:2018-04-20 16:47:03

标签: c# .net automapper dto

我在尸体上的WebApi控制器上发了一个匿名类型的帖子我有new { Firstname = "AA", Lastname = "BB"}

[HttpPost]
public IHttpActionResult Post([FromBody]dynamic person)
{
}

当我点击控制器时,person不为空,我可以看到属性及其数据。

在控制器中,我想将dynamic类型转换为具体类型Person

public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

我尝试了Mapper.Initialize(cfg => cfg.CreateMap<dynamic, Person>());

当我这样做时

var person = Mapper.Map<dynamic, Person>(source);

person的所有属性均为null

有什么想法吗?

谢谢,

1 个答案:

答案 0 :(得分:1)

根据documentation,而不是......

    var person = Mapper.Map<dynamic, Person>(source);

...只是使用......

    var person = Mapper.Map<Person>(source);

完整示例:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public override string ToString() { return FirstName + " " + LastName; }
}

//Main
Mapper.Initialize( cfg => {} );
dynamic source = new ExpandoObject();
source.FirstName = "Hello";
source.LastName = "World";
var person = Mapper.Map<Person>(source);

Console.WriteLine("GetType()= '{0}' ToString()= '{1}'", person.GetType().Name, person);

输出:

GetType()= 'Person' ToString()= 'Hello World'

Link to DotNetFiddle demo