0
votes

I am trying to map a source type to two destination types by using AutoMapper:

public class Source
{
    public string Value1 { get; set; }

    public string Value2 { get; set; }

    public Source[] Values { get; set; }
}

public interface IDest
{
}

public class DestinationSimple : IDest
{
    public string Value1 { get; set; }
}

public class DestinationComplex : IDest
{
    public string Value2 { get; set; }

    public IDest[] Values { get; set; }
}

Destination type to map to should be based on the property values in the source type. If Value1 in Source is not null, destination type should be DestinationSimple. Otherwise destination type should be DestinationComplex.

Which way is the best to proceed? I have tried to use a custom type converter, but I couldn't get it to work because I didn't know how to handle the Values property.

1
I would take a step back and ask yourself if you should really be storing SourceSimple and SourceComplex in one class and doing funny logic to handle it. Can you determine in advance which type you're trying to access? Because you can instead create 2 different execution paths depending on the answer to that question. - C Bauer
SourceSimple and SourceComplex should perhaps not be stored in one class. But the class is given to me, so it's not too easy to change that. I'm afraid I can't in advance determine which type I'm trying to access. - user3660151

1 Answers

0
votes

Here's one way you could do this using a custom type converter:

public class IDestConverter : TypeConverter<Source, IDest>
{
    protected override IDest ConvertCore(Source src)
    {
        IDest result = null;

        if (src.Value1 != null)
        {
            result = new DestinationSimple
            {
                Value1 = src.Value1
            };
        }
        else 
        {
            result = new DestinationComplex
            {
                Value2 = src.Value2,
                Values = Mapper.Map<IDest[]>(src.Values)
            };
        }

        return result;
    }
}

Usage:

Mapper.CreateMap<Source, IDest>()
    .ConvertUsing<IDestConverter>();