Reputation: 2209
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));
.
XElement xe = new XElement("root",
new XElement("parent",
new XAttribute("id", "123"),
new XElement("child", "some text")));
public record ParentRecord(long Id, ChildRecord Child);
public record ChildRecord(string Text);
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();
var o = mapper.Map<ParentRecord>(xe.Element("parent"));
Upvotes: 0
Views: 269
Reputation: 3516
You need the context mapper, smth like ctx.Mapper.Map<ChildRecord>(source)
.
Upvotes: 1