Simple generic model mapper in c#
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;
}
}
}
var destinationModel = ModelMapper.Map<SourceModel, DestinationModel>(sourceModelObject);
No comments:
Post a Comment