phil
phil

Reputation: 2209

Automapper and nested records

I want to map an XML fragment to a record and its nested record. I assume I have to use ConstructUsing() in order to be able to supply all required constructor parameters.

In the CreateMap for parent I don't know how to specify the second parameter without going into some kind of re-entrant hell? I'm guessing I have to reference the mapper that's created in my Startup.cs perhaps. Then I could specify: return new ParentRecord(ele.Attribute("id").Value, mapper.Map<ChildRecord>(ele));.

XML Fragment

XElement xe = new XElement("root",
        new XElement("parent",
            new XAttribute("id", "123"),
            new XElement("child", "some text")));

Records

public record ParentRecord(long Id, ChildRecord Child);

public record ChildRecord(string Text);

Mapping Configuration

var configuration = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<XElement, ChildRecord>()
            .ConstructUsing((ele, ctx) =>
            {
                return new ChildRecord(ele.Element("child").Value);
            });
        cfg.CreateMap<XElement, ParentRecord>()
            .ConstructUsing((ele, ctx) =>
            {
                
                return new ParentRecord(ele.Attribute("id").Value, ?WHAT_TO_PUT_HERE?);
            });
        });
    
    var mapper = configuration.CreateMapper();

Map Request

var o = mapper.Map<ParentRecord>(xe.Element("parent"));

Upvotes: 0

Views: 269

Answers (1)

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

You need the context mapper, smth like ctx.Mapper.Map<ChildRecord>(source).

Upvotes: 1

Related Questions