Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I completely misunderstood what you were trying to do in my original answer. You can accomplish what you want by implementing part of the functionality of AutoMapper using reflection. It will be of very limited utility and the more you extend it, the more like AutoMapper it will be so I'm not sure that there's any long term value to it.</p> <p>I do use a small utility like what you are wanting to automate my auditing framework to copy data from a entity model to its associated audit model. I created it before I started using AutoMapper and haven't replaced it. I call it a ReflectionHelper, the below code is a modification of that (from memory) -- it only handles simple properties but can be adapted to support nested models and collections if need be. It's convention-based, assuming that properties with the same name correspond and have the same type. Properties that don't exist on the type being copied to are simply ignored.</p> <pre><code>public static class ReflectionHelper { public static T CreateFrom&lt;T,U&gt;( U from ) where T : class, new where U : class { var to = Activator.CreateInstance&lt;T&gt;(); 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; } </code></pre> <p>Used as</p> <pre><code> var model = ReflectionHelper.CreateFrom&lt;ViewModel,Model&gt;( entity ); var entity = ReflectionHelper.CreateFrom&lt;Model,ViewModel&gt;( model ); </code></pre> <p><strong>Original</strong></p> <p>I do my mapping in a static constructor. The mapper is initialized the first time the class is referenced without having to call any methods. I don't make the logic class static, however, to enhance its testability and the testability of classes using it as a dependency.</p> <pre><code>public class BusinessLogicAutomapper { static BusinessLogicAutomapper { Mapper.CreateMap&lt;Post, PostModel&gt;(); Mapper.AssertConfigurationIsValid(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload