Automapper: how to display a nested object?

I am struggling with Automapper syntax. I have a list of PropertySurveys, each of which contains 1 Property. I want to map each item in the collection to a new object that combines 2 classes.

So my code is as follows:

            var propertySurveys = new List<PropertyToSurveyOutput >();
            foreach (var item in items)
            {
                Mapper.CreateMap<Property, PropertyToSurveyOutput >();
                var property = Mapper.Map<PropertyToSurvey>(item.Property);
                Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput >();
                property = Mapper.Map<PropertyToSurvey>(item);
                propertySurveys.Add(property);
            }

My simplified classes look like this:

public class Property
{
    public string PropertyName { get; set; }
}

public class PropertySurvey
{
    public string PropertySurveyName { get; set; }
    public Property Property { get; set;}
}

public class PropertyToSurveyOutput
{
    public string PropertyName { get; set; }
    public string PropertySurveyName { get; set; }
}

So, in the PropertyToSurveyOutput object, after the first matching PropertyName. Then, after the second display, the PropertySurveyName is set, but the PropertyName is overridden to null. How to fix it?

+4
source share
2 answers

First of all, Automapper supports collection mapping. You do not need to display each element in a loop.

- , . ( ).

- Automapper , :

Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>()
   .ForMember(pts => pts.PropertyName, opt => opt.MapFrom(ps => ps.Property.PropertyName));

:

var items = new List<PropertySurvey>
{
    new PropertySurvey { 
          PropertySurveyName = "Foo", 
          Property = new Property { PropertyName = "X" } },
    new PropertySurvey { 
          PropertySurveyName = "Bar", 
          Property = new Property { PropertyName = "Y" } }
};

var propertySurveys = Mapper.Map<List<PropertyToSurveyOutput>>(items);

:

[
  {
    "PropertyName": "X",
    "PropertySurveyName": "Foo"
  },
  {
    "PropertyName": "Y",
    "PropertySurveyName": "Bar"
  }
]

UPDATE: Property , - Property:

Mapper.CreateMap<Property, PropertyToSurveyOutput>();

PropertySurvey. PropertySurvey:

Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>()
      .AfterMap((ps, pst) => Mapper.Map(ps.Property, pst));
+4

automapper , , "", - "PropertyName", ,

0

Source: https://habr.com/ru/post/1619931/


All Articles