automapper optimization mapping (model to view model -> get latest version)

459 Views Asked by At

I am trying to optimize this part of code:

   Mapper.CreateMap<Document, DocumentViewModel>()
        .ForMember(g => g.Id, map => map.MapFrom(d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().Id))
        .ForMember(g => g.IdRootDocument, map => map.MapFrom(d => d.Id))
        .ForMember(g => g.certyficateType, map => map.MapFrom(d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().certyficateType))

I'm Using automapper, and I'm trying to optimize this part of code

In this part I'm trying mapping object from document to documentViewModel, in this complex model, source data always will be latest document version:

d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().myProportyX

Could anyone offer an example or suggestion as to how to approach optimization in this situation?

2

There are 2 best solutions below

0
On

d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().myProporty

You are iterating quite a few times here, you may consider doing something like:

d.documentVersion.OrderByDescending(v => v.version).ThenByDescending(v => v.subVersion).First().myProperty

to reduce the number of iterations and only get the top version/subversion.

0
On

optimization mapping:

       Mapper
            .CreateMap<Document, DocumentViewModel>()
            .ConvertUsing(doc =>
                   {
                       DocumentViewModel result = new DocumentViewModel();
                       DocumentVersion lastVersion = doc.documentVersion.Where(v => v.version == doc.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First();
                       Mapper.Map(lastVersion, result);
                       return result;
                   });