'Map two classes in runtime using column mapping information provided in a JSON file
I have two Classes like this.
public class InputModel
{
public int studentid { get; set; }
public string studentname { get; set; }
public string studentcity { get; set; }
}
public class OutputModel
{
public int StudentIDColumn { get; set; }
public string StudentNameColumn { get; set; }
public string StudentCityColumn { get; set; }
}
Now the requirement is like this:
I will receive an object of InputModel Class. From this, I need to create an object of OutputModel class.
It's simple if we use a library like AutoMapper. But the problem is, the Column-To-Column Mapping information will be supplied via a Json File like this:
{
"studentid": "StudentIDColumn",
"studentname": "StudentNameColumn",
"studentcity": "StudentCityColumn"
}
Based on the JSON mapping data, I need to Map the columns in runtime and generate the Output class object.
I tried to map the two classes using Automapper. But I am not sure how to do it in runtime using the JSON file.
var MapperConfig = new MapperConfiguration(c =>
c.CreateMap<InputCSVModel, OutputIDMModel>()
.ForMember(dest => dest.StudentIDColumn, act => act.MapFrom(src => src.studentid))
.ForMember(dest => dest.StudentNameColumn, act => act.MapFrom(src => src.studentname))
.ForMember(dest => dest.StudentCityColumn, act => act.MapFrom(src => src.studentcity))
);
var mapper = new Mapper(MapperConfig);
OutputIDMModel outModel = mapper.Map<OutputIDMModel>(inputModel);
I know that it's might be possible to do this with Reflection. But is there any better approach ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
