Angelo Meneses
Angelo Meneses

Reputation: 21

Map Different Concrete Types to Collection of Interface

I'm having difficulty in mapping different concrete types to a single collection of interface in automapper. For example:

Domain:

public interface INameInterface {
    string Name;
}

public class FullName: INameInterface {
    string Name;
}

public class FirstNameOnly: INameInterface {
    string Name;
}

public class MyDomain {
    List<INameInterface> Names;
}

DTOs:

public class NameDTO {
    int NameType;
    string Name;
}

public class MyDTO {
    List<NameDTO> NameDTOs;
}

I would like to map MyDTO to MyDomain. I would like to resolve NameDTO by its NameType and map NameTypes 1 to Fullname and 2 to FirstNameOnly concrete classes and place them in MyDomain.Names collection. How can I do it in automapper.

Any help is highly appreciated.

PS. Example is simplified

Upvotes: 1

Views: 118

Answers (1)

Angelo Meneses
Angelo Meneses

Reputation: 21

This can be solved using custom type converter.

In automapper config:

cfg.CreateMap<NameDTO, INameInterface>()
                    .ConvertUsing<SomeConverter>();

Then create the custom converter class.

public class SomeConverter : ITypeConverter<NameDTO, INameInterface>
{
    public INameInterface Convert(NameDTO source, INameInterface destination, ResolutionContext context)
    {
        if (source.NameType == 0)
        {
            return context.Mapper.Map<FullName>(source);
        }
        if (source.NameType == 1)
        {
            return context.Mapper.Map<FirstNameOnly>(source);
        }

        return context.Mapper.Map<FirstNameOnly>(source);
    }
}

Just add the necessary mapping for each concrete types.

Warning tho, I have tried to use this approach in projection but this won't work as it cannot be converted to an expression.

Upvotes: 1

Related Questions