How to map a single property to each element's property of a collection using AutoMapper?

StackOverflow https://stackoverflow.com/questions/22790203

  •  25-06-2023
  •  | 
  •  

Question

I want to map Parent to ParentMapped and Child should be mapped to ChildMapped, but the source for ChildMapped is also Parent since ChildMapped's SomeFlag Property should be sourced by Parent's SomeFlag Property. Classes look like this:

    public class Parent
{
    public bool SomeFlag { get; set; }
    public List<Child> Children { get; set; }
}

public class ParentMapped
{
    public List<ChildMapped> Children { get; set; }
}

public class Child
{
}

public class ChildMapped
{
    public bool SomeFlag { get; set; }
}

Let's assume structure of Parent and Child classes cannot be modified. I tried configuring the mappings like this:

Mapper.CreateMap<Parent, ParentMapped>();
Mapper.CreateMap<Child, ChildMapped>();
Mapper.CreateMap<Parent,ChildMapped>()
      .ForMember(dest => dest.SomeFlag, opt => opt.MapFrom(src => src));

and do the mapping by calling like this:

var instanceOfParent = new Parent();
var intanceOfParentMapped = mapper.Map<ParentMapped>(instanceOfParent);

But this solution does not work.

Is this kind of mapping even possible with AutoMapper?

Était-ce utile?

La solution

You can define an action to run after the mapping:

Mapper.CreateMap<Parent, ParentMapped>()
    .AfterMap((m,d) => d.Children.ForEach(c => c.SomeFlag = m.SomeFlag));

Autres conseils

One way would be to add a Parent property to the Child and then do a ForMember(x => x.SomeFlag, opt => opt.MapsFrom(src => src.Parent.SomeFlag).

Alternatively, you could use a ConstructUsing method for the parent but there would be little point using AutoMapper if you went that way.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top