AutoMapper - Dynamic & ExpandoObjects

Automapper supports dynamic and ExpandoObjects and will map to/from without any additional configuration. In the example given below, mapping is done from a ExpandoObject(viewModel) to an instance of ModelData class(model)

The members for the source are dynamically created and AutoMapper maps it properly without any explicit configuration. You can see that which create the configuration object have an empty lambda expression.

using System;
using AutoMapper;
using System.Dynamic;

namespace AutoMapperSamples.Configuration
{
    namespace AutoMapperSample
    {

        public class ModelData
        {
            public string Name { get; set; }
            public DateTime StartedOn { get; set; }


        }
        
        public class TestAutoMapper
        {

            public static void Main()
            {

                dynamic viewModel = new ExpandoObject();
                viewModel.Name = "Bridge Construction";
                viewModel.StartedOn = DateTime.Now;
                var config = new MapperConfiguration(cfg => { });

                config.AssertConfigurationIsValid();


                var model = new ModelData { StartedOn = DateTime.Now, Name = "Bridge Construction" };

                model = config.CreateMapper().Map<modeldata>(viewModel);
                Console.WriteLine("\nName " + model.Name);
                Console.WriteLine("\nStart Date " + model.StartedOn);



                Console.ReadKey();
            }
        }
    }
}

Output


No Comments

Add a Comment