AutoMapper: string for nullable int

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?

+6
source share
1 answer

I think that the error you see hides the actual problem, which is that the compiler cannot determine what type you want to get from the conditional:

 string.IsNullOrWhiteSpace(src.ReportsToEmployeeId) ? null : int.Parse(src.ReportsToEmployeeId) 

Here, the compiler does not know that you want a Nullable<int> as a result of evaluating the conditional statement. null has no type, so you need to attribute it to int? :

 string.IsNullOrWhiteSpace(src.ReportsToEmployeeId) ? (int?)null : int.Parse(src.ReportsToEmployeeId) 

Or can you use default(int?) Or new int?() , Or pass the result of int.Parse to int? .

+6
source

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


All Articles