Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Okay, I think I've figured this out:</p> <ul> <li><p>With an <code>IValueFormatter</code>, the input to the <code>FormatValue()</code> method is the actual value. (Okay, technically, it's a <code>ResolutionContext</code> object that lets you get at the value using the <code>SourceValue</code> property, but you get the idea).</p></li> <li><p>With a <code>ValueResolver</code>, the input to the <code>ResolveCore()</code> method is the entire source (not just the source value).</p></li> </ul> <p>So, if you want to do some kind of conversion between a source value and a destination value, an <code>IValueFormatter</code> will only work if the destination type is a <code>string</code>, and a <code>ValueResolver</code> will only work if the <code>ResolveCore()</code> method "knows" which property to use (which won't be the case if your resolver is general purpose, i.e., doesn't apply to a particular property).</p> <p><strong>Workaround</strong></p> <p>Fortunately, there is always <code>MapFrom</code>, which provides the flexibility that is lacking with both resolvers and formatters.</p> <p><strong>Converter interface</strong></p> <p>I ended up writing an interface to simply and flexibly handle what I believe is a very common scenario: two-way conversions...</p> <pre><code>public interface ITwoWayConverter&lt;TInput, TOutput&gt; { TOutput ConvertForward(TInput value); TInput ConvertBackward(TOutput value); } </code></pre> <p><strong>Example converter:</strong></p> <pre><code>public class PhoneNumberToString : ITwoWayConverter&lt;long, string&gt; { public string ConvertForward(long value) { return string.Format("{0:(###) ###-####}", Convert.ToInt64(value)); } public long ConvertBackward(string value) { return Convert.ToInt64(Regex.Replace(value, @"\D", string.Empty)); } } </code></pre> <p><strong>Example usage:</strong></p> <pre><code>Mapper.CreateMap&lt;User, UserViewModel&gt;() .ForMember(dest =&gt; dest.PhoneNumber, opt =&gt; opt .MapFrom(orig =&gt; new PhoneNumberToString().ConvertForward(orig.PhoneNumber))); </code></pre>
 

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