I completely misunderstood what you were trying to do in your original answer. You can accomplish what you want by implementing some of the AutoMapper functions using reflection. It will be a very limited utility, and the more you expand it, the more it looks like AutoMapper, so I'm not sure if it has long-term value.
I use a small utility, for example, that you want to automate my audit structure in order to copy data from the entity model into the associated audit model. I created it before I started using AutoMapper and did not replace it. I call it ReflectionHelper, the code below is a modification of this (from memory) - it processes only simple properties, but can be adapted to support nested models and collections, if necessary. It is based on consensus, assuming that properties with the same name correspond and are of the same type. Properties that do not exist for the type being copied are simply ignored.
public static class ReflectionHelper { public static T CreateFrom<T,U>( U from ) where T : class, new where U : class { var to = Activator.CreateInstance<T>(); var toType = typeof(T); var fromType = typeof(U); foreach (var toProperty in toType.GetProperties()) { var fromProperty = fromType.GetProperty( toProperty.Name ); if (fromProperty != null) { toProperty.SetValue( to, fromProperty.GetValue( from, null), null ); } } return to; }
Used as
var model = ReflectionHelper.CreateFrom<ViewModel,Model>( entity ); var entity = ReflectionHelper.CreateFrom<Model,ViewModel>( model );
Original
I am doing the matching in a static constructor. The initializer is initialized the first time the class is accessed without calling any methods. However, I did not set a static logic class to increase its testability and testability of classes, using it as a dependency.
public class BusinessLogicAutomapper { static BusinessLogicAutomapper { Mapper.CreateMap<Post, PostModel>(); Mapper.AssertConfigurationIsValid(); } }
source share