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
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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));

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top