Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to define AutoMapper mapping outside code i.e. in a XML file or use different approach for a fully configurable object mapping?
    text
    copied!<p><strong>EDIT:</strong> Originally I intended to use AutoMapper to achieve my goal, but I had to learn that AutoMapper is not intended to work that way. It gives you the possibility to create profiles but in my case (fully configurable) I would need for each parameter combination one profile, so I came up with an own approach, see answers.</p> <p>From the AutoMapper wiki I learned to create a simple mapping like </p> <pre><code> Mapper.CreateMap&lt;CalendarEvent, CalendarEventForm&gt;().ForMember(dest =&gt; dest.Title, opt =&gt; opt.MapFrom(src =&gt; src.Title)); Mapper.CreateMap&lt;CalendarEvent, CalendarEventForm&gt;().ForMember(dest =&gt; dest.EventDate, opt =&gt; opt.MapFrom(src =&gt; src.EventDate.Date)); Mapper.CreateMap&lt;CalendarEvent, CalendarEventForm&gt;().ForMember(dest =&gt; dest.EventHour, opt =&gt; opt.MapFrom(src =&gt; src.EventDate.Hour)); Mapper.CreateMap&lt;CalendarEvent, CalendarEventForm&gt;().ForMember(dest =&gt; dest.EventMinute, opt =&gt; opt.MapFrom(src =&gt; src.EventDate.Minute)); </code></pre> <p>For two classes like</p> <pre><code>public class CalendarEvent { public DateTime EventDate; public string Title; } public class CalendarEventForm { public DateTime EventDate { get; set; } public int EventHour { get; set; } public int EventMinute { get; set; } public string Title { get; set; } } </code></pre> <p>I was now wondering if there is a possibility to define the mapping externally i.e. in an XML file like</p> <pre><code>&lt;ObjectMapping&gt; &lt;mapping&gt; &lt;src&gt;Title&lt;/src&gt; &lt;dest&gt;Tile&lt;/dest&gt; &lt;/mapping&gt; &lt;mapping&gt; &lt;src&gt;EventDate.Date&lt;/src&gt; &lt;dest&gt;EventDate&lt;/dest&gt; &lt;/mapping&gt; &lt;mapping&gt; &lt;src&gt;EventDate.Hour&lt;/src&gt; &lt;dest&gt;EventHour&lt;/dest&gt; &lt;/mapping&gt; &lt;mapping&gt; &lt;src&gt;EventDate.Minute&lt;/src&gt; &lt;dest&gt;EventMinute&lt;/dest&gt; &lt;/mapping&gt; </code></pre> <p></p> <p>and by that influence the creation of the map (XML isn't a reqirement, can be everything else too). For simplicity say types are no issue, so src and dest should be the same otherwise it is ok to fail. The idea behind this is to be very flexible in what should be mapped and where it should be mapped. I was thinking about reflection to get property values based on its name, but this seems to not work. I'm also not sure if this makes sense at all or if I'm missing something important, so help and ideas are appreciated.</p>
 

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