Reputation: 860
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> Provider { get; set; }
}
I've initialized my mapping by using the following code
CreateMap<SourceClass, DestinationClass>();
And then in my controller, I have :
Mapper.Map<List<DestinationClass>>(requests)
where "requests" is a List of SourceClass objects being passed in to my controller.
My question is, how can I map the Provider(of type string) in my SourceClass to Provider(of type List in my Destination class?
The provider in sourceclass will always be a single string, and provider in the destination class will always be a list of a single string.
Here is what I've tried in the mapping configurations:
CreateMap<SourceClass, DestinationClass>().ForMember(destinationMember => destinationMember.Provider,
memberOptions => memberOptions.MapFrom(src => {
return string.IsNullOrEmpty(src.Provider) ? [""] : src.Provider.ToList());
Upvotes: 0
Views: 1548
Reputation: 73
Replace your mapping configuration with this one:
CreateMap<SourceClass, DestinationClass>()
.ForMember(destinationMember => destinationMember.Provider,
memberOptions => memberOptions
.MapFrom(src =>
{
return new List<string>{ string.IsNullOrEmpty(src.Provider) ? "" : src.Provider)
});
Upvotes: 0
Reputation: 346
If you cast your source member's Provider property to a List, you would get a List of char type. This code should reflect what you need.
CreateMap<SourceClass, DestinationClass>()
.ForMember(
destinationMember => destinationMember.Provider,
memberOptions => memberOptions.MapFrom(
src => string.IsNullOrEmpty(src.Provider) ? new List<string>() { "" } : new List<string> { src.Provider }
)
);
Upvotes: 0
Reputation: 897
First off I'd recommend renaming your destination property to Providers
to avoid confusion/represent that it is a collection. Then you could give this a try
CreateMap<SourceClass, DestinationClass>()
.ForMember(destinationMember => destinationMember.Providers,
memberOptions => memberOptions.MapFrom(src => new List<string> {src.Provider ?? ""}));
Specifically this bit
src => new List<string> {src.Provider ?? ""}
Creates a new list of type string with one value, either src.Provider
, or if that is null, an empty string.
Upvotes: 2