AutoMapper: Int to String and vice versa

EDIT: enable TypeConverter

To set up the scene, I delete the code from the existing WCF service to be placed in the business object (BO) that WCF will reference to provide information to clients. The requirement is to force the employeeId of the Employee object to be an integer, rather than the currently used string. I use AutoMapper to map all objects between BO and WCF so that contracts are not interrupted. However, I am struggling with how to provide a back and forth mapping so that EmployeeId is an integer in BO and is still contractually serving strings through WCF.

BO

public class Employee { public int Id {get; set;} ...... } 

FOS

 [DataContract(Name = "Employee", Namespace="url")] public class Employee { [DataMember(Order = 1)] public string Id {get; set;} ...... } 

Chart maker

 Mapper.CreateMap<Employee.Entity.Employee, Employee.Service.Entity.Employee>() 

PaddedStringTypeConverter Class:

 public class PaddedStringTypeConverter : ITypeConverter<int, string> { public string Convert(ResolutionContext context) { var sourceValue = System.Convert.ToInt32(context.SourceValue); return sourceValue.ToString("D9"); } } 

I saw that I can use Custom Type Converters in AutoMapper to change the BO from an integer to our fixed length of nine characters, so an integer value of 4610 will be equivalent to the string "000004610". However, how do I return it to an integer value.

How do you do this?

+2
source share
2 answers

Automapper is great for automatically displaying in / out objects with the same name. If you want to change the transformation or if the name of the thing you want to map is different, you need to use .ForMember (). Your map will look something like this:

  Mapper.CreateMap<Employee.Entity.Employee, Employee.Service.Entity.Employee>() .ForMember(dest => dest.EmployeeID, expression => expression.MapFrom(src => Convert.ToInt32(src.EmployeeID))) ; 

Then add the reverse user mapping.

You do not need the PaddedStringTypeConverter class.

+2
source

Create two mappings for both directions:

 Mapper.CreateMap<Employee.Entity.Employee, Employee.Service.Entity.Employee>() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString("D9"))) .ReverseMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => int.Parse(src))); 

This creates maps in both directions, and the options convert the types for this element back and forth.

ReverseMap is a shortcut to CreateMap with source / destination types enabled.

0
source

Source: https://habr.com/ru/post/973823/


All Articles