Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper and Sorting the child collection conditionally

I have an object graph that I'm loading from a database using Fluent NHibernate and AutoMapper into DTOs:-

public class Foo
{
  public int Id { get; set; }
  public virtual ICollection<Bar> Bars { get; set; }
  public bool SortBarByName
}

public class Bar
{
  public int Id { get; set; }
  public int SortOrder { get; set; }
  public virtual Foo Foo { get; set; }
}

My mappings look like:-

public class FooDto
{
  public IEnumerable<BarDto> Bars { get; set; }
}

public class BarDto
{
  public string Name { get; set; }
  public int SortOrder { get; set; }
}

My mapping looks like:

mapper.CreateMap<Foo, FooDto>().ForMember(d => d.Bars, o => o.MapFrom(s => s.Bars));
mapper.CreateMap<Bar, BarDto>();

When I return FooDto, I want collection of BarDto to be sorted based on below condition. I want to sort BarDto by Name if SortBarByName is true or by SortOrder if SortBarByName is false, based on SortBarByName property of class Foo.

Note: Name property is not present in Bar class, it is only in BarDto.

Can I do something in the AutoMappers to achieve this?

like image 352
9_A Avatar asked Nov 12 '18 06:11

9_A


1 Answers

Since one of the properties you want to use for the order is only available after you mapped the data you can use the AfterMap() functionality of AutoMapper like this:

mapper.CreateMap<Foo, FooDto>()
                .AfterMap(
                    (foo, dto) =>
                    {
                        dto.Bars = foo.SortBarByName
                            ? dto.Bars.OrderBy(x => x.Name)
                            : dto.Bars.OrderBy(x => x.SortOrder);
                    });

This should order the Bars after all data is available.

like image 81
RedFox Avatar answered Nov 12 '22 13:11

RedFox