Greg B
Greg B

Reputation: 14898

Can I specify a default mapping source for unmapped members with AutoMapper?

I have a type that encapsulates a bunch of related data

class CollectionNoteDetails
{
    CollectionNote Note {get;set;}
    Customer SourceCustomer {get;set;}
    Customer DestinationCustomer {get;set;}
    Haulier Haulier{ get;set;}
}

and I want to flatten it

class CollectionNoteDto
{
    // using fields for brevity

    int Id;
    DateTime CollectionDate;
    // ... plus about 30 more props

    string SourceCustomerName;
    string DestinationCustomerName;
    string HaulierName;
}

there's about 30 properties on the DTO that come off the CollectionNote, and a few that come off the other entities. The other entities are easy to handle in the CreateMap() call:

CreateMap<CollectionNoteDetails, CollectionNoteDoc>(MemberList.Destination)
    .ForMember(d => d.SourceCustomerName, o => o.MapFrom(s => s.SourceCustomer.Name))
     .ForMember(d => d.DestinationCustomerName, o => o.MapFrom(s => s.DestinationCustomer.Name))
     .ForMember(d => d.HaulierName, o => o.MapFrom(s => s.Haulier.Name));

... but is there an easy way to map the rest of the properties to the Note source property? Something like this made up method.

CreateMap<CollectionNoteDetails, CollectionNoteDoc>(MemberList.Destination)
   .MapAllByDefault(o => o.MapFrom(s => s.Note))
   // other explicit mappings here
   .ForMember(d => d.HaulierName, o => o.MapFrom(s => s.Haulier.Name));

Upvotes: 0

Views: 96

Answers (1)

Oignon_Rouge
Oignon_Rouge

Reputation: 307

You might need to recognize a prefix. The example from the documentation:

public class Source {
    public int frmValue { get; set; }
    public int frmValue2 { get; set; }
}
public class Dest {
    public int Value { get; set; }
    public int Value2 { get; set; }
}
var configuration = new MapperConfiguration(cfg => {
    cfg.RecognizePrefixes("frm");
    cfg.CreateMap<Source, Dest>();
});

On different matters, note that flattening is automatically supported by automapper, which means that this code:

CreateMap<CollectionNoteDetails, CollectionNoteDoc>(MemberList.Destination)
    .ForMember(d => d.SourceCustomerName, o => o.MapFrom(s => s.SourceCustomer.Name))
     .ForMember(d => d.DestinationCustomerName, o => o.MapFrom(s => s.DestinationCustomer.Name))
     .ForMember(d => d.HaulierName, o => o.MapFrom(s => s.Haulier.Name));

is equivalent to:

CreateMap<CollectionNoteDetails, CollectionNoteDoc>(MemberList.Destination);

Upvotes: 0

Related Questions