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)));
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
The problem you may face is when it is unable to parse the string, one option would be to use a ResolveUsing:
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.intphoneno, opts => opts.ResolveUsing(src =>
double.TryParse(src.strphoneno, out var phoneNo) ? phoneNo : default(double)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With