Auto Mapper convert from string to Int

user2739679 picture user2739679 · Sep 12, 2013 · Viewed 24.8k times · Source

I am creating a simple MVC4 application

I have a automapper

 Mapper.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Stringphoneno));

IntphoneNo is of DataType int ( IntphoneNo is an variable of my class Person) Source attribute Stringphoneno is of Datatype string.

When i am mapping , i am getting follwoing error.

An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code

But when i am changing the Dataype of IntphoneNo from int to string then my program is running successfully.

Unfortunately i cant change the Datatype inmy model

Is theer any way to change Datatupe in mapping .. Something like below

.ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Int32(Stringphoneno));

After some research I came one step futher ..
If my StringPhoneNo is = 123456
then follwoing code is working. I dont need to parse it to string

Mapper.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Stringphoneno));

but when my StringPhoneNo is = 12 3456 ( there is a space after 12) then my code is not working. Is there any way to trim spaces in Stringphoneno (Stringphoneno i am geting from webservice) in automapper.

Something like below..

Mapper.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Trim(Stringphoneno))); 

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Sep 12, 2013
Mapper.CreateMap<SourceClass, DestinationClass>() 
    .ForMember(dest => dest.IntphoneNo, 
        opt => opt.MapFrom(src => int.Parse(src.Stringphoneno)));

Here is some sample working code using the map described

class SourceClass
{
    public string Stringphoneno { get; set; }
}

class DestinationClass
{
    public int IntphoneNo { get; set; }
}

var source = new SourceClass {Stringphoneno = "8675309"};
var destination = Mapper.Map<SourceClass, DestinationClass>(source);

Console.WriteLine(destination.IntphoneNo); //8675309