Monday, May 28, 2018

Simple generic model mapper in c#


During development we can have many cases where model mapping is required. YES, there are already many tools for this purpose eg Automapper. Well, below you can find a generic function which maps a model to another.

TSource is the source class and TDestination is the destination class. The function returns an object of TDestination class. For properties in destination class, it tries to map available mapping values in source class.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace MapperTools
{
    public static class ModelMapper 
    {        
        public static TDestination Map<TSource, TDestination>(TSource sourceObj) where TDestination : class, new()
        {
            TDestination returnObj = new TDestination();
            foreach (var returnPropertyInfo in returnObj.GetType().GetProperties())
            {
                var sourcePropertyInfo = sourceObj.GetType().GetProperty(returnPropertyInfo.Name);
                if (sourcePropertyInfo != null)
                {
                    var sourceValue = sourcePropertyInfo.GetValue(sourceObj);
                    returnPropertyInfo.SetValue(returnObj, sourceValue);
                }                
            }           
            return returnObj;
        }

    }
}

Use :
var destinationModel = ModelMapper.Map<SourceModel, DestinationModel>(sourceModelObject);