60865

Is there a way in AutoMapper to specify that all strings being mapped are to be trimmed

Question:

I'm converting a WinForms app to ASP.NET MVC4 and trying to implement a ViewModel approach using AutoMapper to map between the domain entities and the ViewModels, mostly to flatten the more complex object graphs into ViewModels for easy binding in the views.

The problem I'm running into is that when leaving some fields blank that the domain model wants to apply a Trim() a NullReferenceException is thrown.

Originally this was all handled in the domain objects for example in the Customer object I have a string property that trims to ensure whatever value was passed in is trimmed, and that way not have to clutter the original WinForms with Trim everywhere the value could be set, just rely on passing it to the domain model and let it set do the Trim or ToUpper as the value was persisted.

public virtual String Name { get { return _name; } set { _name = StringFormatting.ToTitleCase(value.Trim()); } } public virtual String Email { get { return _email; } set { _email = value.Trim(); } }

and in terms of my ViewModel I've just got auto implemented properties:

public class CustomerCreateViewModel { [Required(ErrorMessage="Please enter a name for this customer")] public string Name { get; set; } [DataType(DataType.EmailAddress)] public string Email { get; set; } }

However if the email textbox is empty when the form is submitted then a NullReferenceException would be thrown on

<blockquote>

set { _email = value.Trim() ; }

</blockquote>

To get around that I added a setter guard clause

public virtual String Email { get { return _email; } set { if (_email == value) return; _email = value.Trim(); } }

and that <em>worked</em> in that the error with that field went away, but it moved to the next property, Mobile - which I repeated the fix for and then on to the next and the next and the next. None of these are required so it is correct for them to be passed in empty.

Is there a way in AutoMapper to specify that all strings being mapped are to be trimmed? Am I approaching this wrongly; is it not necessary to Trim strings? Or whereabouts should that trimming be performed, my preference would be to only need to trim strings as they're submitted, but not in the code for any individual controller, it feels like it should be done somewhere in the ViewModel / Domain model, but where?

Answer1:

You can use ITypeConverter<M,V> like so...

public class ModelToViewModelConverter : ITypeConverter<Model, ViewModel> { public UIItemViewModel Convert(ResolutionContext context) { Model model = (Model)context.SourceValue; // Perform your logic } }

Answer2:

As alternative and easier solution

Mapper.CreateMap<string, string>().ConvertUsing( str => !string.IsNullOrEmpty(str) ? str.Trim() : null );

Recommend

  • Date Validation in JSF & Richfaces
  • Why LINQ to Entities does not recognize the method 'System.String ToString()?
  • Compare adjacent list items
  • After first click, If ajax is done, on second click e.stopPropagation
  • get only value from JSONArray, i.e. without also the key, in java
  • Does the Xml Schema spec define the serialization of optional attributes with a default?
  • The Vigenere algorithm in C# explanation
  • java.lang.UnsatisfiedLinkError when using JNI on ubuntu
  • Manually insert an item into a ListView control
  • hough transform error in matlab and openCV?
  • Set PageIndex of DataPager
  • A more compact representation than BASE64 for byte arrays?
  • Firebase Authentication Javascript: setCookie for pending Credential for redirect
  • Rounding returned float values from a DB to their 'correct' values
  • R replacing columns by lookup to dictionary
  • Request map direct me to Login page in Grails
  • Fastest way to save/load data.table
  • R matching more than 2 conditions and return the response value
  • Validity Method for Reference Classes
  • Oracle - Second level subquery cannot see field from main query
  • Activation Function choice for Neural network
  • Getting the scrolling offset when storing coordinates
  • cordova is not defined - cordova.js has already been loaded :: Ionic
  • Who propagate bugfixes across branches (corporate development)?
  • Android Studio Can't Find tools.jar
  • UWP/C# - Issue with AQS and USB Devices
  • xcode don't localize specific strings
  • How to assign byte[] as a pointer in C#
  • Calling Worksheet functions from vba in foreign language versions of Excel
  • Ensure fsync did its job
  • Do I need to reset a Perl hash index?
  • ilmerge with a PFX file
  • Java applet as stand-alone Windows application?
  • Updating server-side rendering client-side
  • javascript inside java/jsp code
  • How to set the response of a form post action to a iframe source?
  • Change div Background jquery
  • Qt: Run a script BEFORE make
  • Running Map reduces the dimensions of the matrices
  • reshape alternating columns in less time and using less memory