I have the following two classes:
I have two classes
public class SourceClass
{
public Guid Id { get; set; }
public string Provider { get; set; }
}
public class DestinationClass
{
public Guid Id { get; set; }
public List<string> Providers { get; set; }
}
I have the following mappings for my automapper
CreateMap<SourceClass, DestinationClass>()
.ForMember(destinationMember => destinationMember.Providers,
memberOptions => memberOptions.MapFrom(src => new List<string> {src.Provider ?? ""}));
CreateMap<DestinationClass, SourceClass>().ForMember(SourceClass => SourceClass.Provider,
memberOptions => memberOptions.MapFrom(src => src.Providers.FirstOrDefault()));
I wrote some unit tests and can confirm the following behaviour:
When Providers in my destination class is null, it maps to null, which is great. However, I'd like to change my mapping so that if Providers is an empty list, it maps to an empty list and similarly, if Provider is null, I'd want it to map to an empty list instead of a list with an empty string.
Does anyone know how I can go about doing this? I've tried this for my mapping from SourceClass to DestinationClass:
CreateMap<SourceClass, DestinationClass>()
.ForMember(destinationMember => destinationMember.Providers,
memberOptions => memberOptions.MapFrom(src => !string.IsNullOrEmpty(src.Provider) ? new List<string> {src.Provider} : new List<string>()));
but for going the other way, an empty list is mapping to null, instead of an empty list. (I think because of FirstOrDefault() ). Does anyone know how I can work around this?
List<String>and Provider is astring. Just to clarify, you want to map it so thatDestination.Providersmaps to an empty list whenSource.Provideris null or empty? - Tyler HundleySource.Providermaps to the first element ofDestination.Providersif it is not empty, or an empty string if it is? - Tyler HundleymemberOptions => memberOptions.MapFrom(src => (src.Providers.Count == 0) ? "" : src.Providers.FirstOrDefault()));- blazerix