This is similar to my previous post ( AutoMapper: Int to String and vice versa) , but this time it touches on another aspect with a zero int.
My business object
public class Employee { .... public int? ReportsToEmployeeId {get; set;} .... }
My WCF
[DataContract(Name="Employee", Namespace="url")] public class Employee { .... [DataMember(Order = 1)] public string ReportsToEmployeeId {get; set;} .... }
Chart maker
Mapper.CreateMap<Employee.Entity.Employee, Employee.Service.Entity.Employee>() .... .ForMember(dest => dest.ReportsToEmployeeId, opt => opt.MapFrom(src => src.ReportsToEmployeeId.HasValue ? src.ReportsToEmployeeId.Value.ToString("D9") : string.Empty)) .... .ReverseMap() .... .ForMember(dest => dest.ReportsToEmployeeId, opt => opt.MapFrom(src => string.IsNullOrWhitespace(src.ReportsToEmployeeId) ? null : int.Parse(src.ReportsToEmployeeId)))
I use the first opt.MapFrom to convert from an integer to a string and feed leading zeros if necessary. The second uses the extension to check whether the string value is empty or empty and assign it to a zero value or parse an integer to fill in the nullable int value. However, I get a build error in the zero segment. The error lies in the simple statement that it has an unknown method for ForMember or MapFrom.
Visual Studio confirms that dest.ReportsToEmployeeId is a null int in the code after the ReverseMap, so it seems strange that it will not accept it. If I changed the code:
.... .ForMember(dest => dest.ReportsToEmployeeId, opt => opt.MapFrom(src => string.IsNullOrWhitespace(src.ReportsToEmployeeId) ? int.Parse(src.ReportsToEmployeeId) : int.Parse(src.ReportsToEmployeeId))) ....
everything seems to be fine. Therefore, I know that this is mapping a null value to a nullable int, causing the problem.
What am I missing? Would there be a better way to approach this?
Hitek source share