The Question
After mapping Input
to Output
, the returned Input
must have an incrementing number in its Entries[i].Id
, (i.e. Entries[0].Id = 1
, Entries[1].Id = 2
, Entries[2].Id = 3
, ...). So I tried to put it in AfterMapping
:
[Mapper]
public interface IMyMapper {
Output Map(Input userTableTemplate);
}
public class RegisterMyMapper : IRegister {
public void Register(TypeAdapterConfig config) {
config.NewConfig<Input, Output>()
.Map(output => output.OutputName, input => input.Name)
.AfterMapping(output => {
foreach (var pair in output.Entries.Select((value, index) => new {value = value, index = index})) {
pair.value.Id = pair.index + 1;
}
});
}
}
public class Output {
public string OutputName { get; set; }
public IEnumerable<Entry> Entries { get; set; }
}
public class Entry { public int Id { get; set; } }
public class Input { public string Name { get; set; } }
But when running _myMapper.Map(myInput)
I'm getting a null reference exception, because the private Action<Output> Action1
member of the generated code (public partial class MyMapper : IIMyMapper
) is null:
public partial class MyMapper : IMyMapper
{
private Action<Output> Action1;
public Output Map(Input p1)
{
if (p1 == null)
{
return null;
}
Output result = new Output();
result.OutputName = p1.Name;
Action1.Invoke(result);
return result;
}
}
Current solution
Switched from AfterMapping
to AfterMappingInline
:
config.NewConfig<Input, Output>()
.Map(output => output.OutputName, input => input.Name)
.AfterMappingInline(output => output.Entries.SetIdValues())
And:
public static class MethodExtensions {
public static void SetIdValues(this IEnumerable<Entry> entries) {
foreach (var pair in entries.Select((value, index) => new {value = value, index = index}))
pair.value.Id = pair.index + 1;
}
}
...was hoping to find more elegant solution...