Mo B.
Mo B.

Reputation: 5805

How to configure AutoMapper to flatten a property?

Suppose we have the following classes:

public class A {
    public B[] Bs { get; set; }
}

public class B {
    public int Id { get; set; }
}

public class C {
    public int[] Xs {get; set; }
}

What's the simplest way to configure AutoMapper to map objects of type A to objects of type C? The intended effect is that A.Bs should get flattened to C.Xs.

Upvotes: 1

Views: 61

Answers (1)

Evk
Evk

Reputation: 101463

Not sure about "simplest", but one way to do that is

Mapper.Initialize(cfg => {
    cfg.CreateMap<A, C>().ForMember(c => c.Xs, c => c.MapFrom(r => r.Bs.Select(a => a.Id)));
});

Upvotes: 1

Related Questions