Search code examples
c#.netautomapperdto

dynamic to concrete type with automapper


I do a post with an anonymous type on an WebApi controller in the body I have this new { Firstname = "AA", Lastname = "BB"}

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

When I hit the controller, person is not null and I can see the the properties with their data.

In the controller I'd like convert the dynamic type to my concrete type Person

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

I tried with Mapper.Initialize(cfg => cfg.CreateMap<dynamic, Person>());

When I do this

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

All the properties of person are null.

Any idea ?

Thanks,


Solution

  • According to the documentation, instead of...

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

    ...just use...

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

    Full example:

    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);
    

    Output:

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

    Link to DotNetFiddle demo