DLeh
DLeh

Reputation: 24395

Automapper - Mapping the index into a property of collection

I'm mapping a domain model to a DTO and vice versa. I'm trying to configure my API to accept a DTO with a collection, where the order of that collection will map to a int Sequence in my domain object for persistence.

public class Model {
    public ICollection<Fields> Fields { get; set; }
}
public class Field {
    public int Sequence { get; set; }
}
CreateMap<ModelView, Model>()
    .ForMember(x => x.Fields, opt => opt...)
    // here I want to specify that currentField.Sequence = Model.Fields.IndexOf(currentField)
    //     , or to set it equal to some counter++;
    ;

Is such a thing possible in Automapper, or would I have to write my own ConstructUsing() method to do this logic? I'm hesitant to use ConstructUsing() because I have a mapping specified for the Field DTO and I don't want to duplicate that logic.

I also would like to be able to configure it so that when I'm going back to my DTO (Model -> ModelView) that I can insert the Fields into the collection in the order specified by Sequence.

Upvotes: 0

Views: 2174

Answers (1)

DLeh
DLeh

Reputation: 24395

I think I found the solution I was looking for. Using AfterMap() I'm able to override these values from being mapped directly:

CreateMap<Model, ModelView>()
    .AfterMap((m, v) =>
    {
        v.Fields = v.Fields?.OrderBy(x => x.Sequence).ToList(); 
        //ensure that the DTO has the fields in the correct order
    })
    ;


CreateMap<ModelView, Model>()
    .AfterMap((v, m) =>
    {
        //override the sequence values based on the order they were provided in the DTO
        var counter = 0;
        foreach (var field in m.Fields)
        {
            field.Sequence = counter++;
        }
    })

Upvotes: 2

Related Questions