I have two applications A and B and I created another API utility between them to map the properties dynamically for every client and then send requests. I have properties mapping information in the JSON.
For example, I have two clients.
Client A want to map Employee properties of A application with B Application like below:
Application A Employee Class Application B Employee Class
FirstName LastName <---------> Name
Description <---------> Title
Title <---------> JobTitle
Client B want to map Employee properties of A application with B Application like below:
Application A Employee Class Application B Employee Class
FirstName LastName <---------> Name
Description <---------> JobTitle
Title <---------> Title
I have some other fields which need to map based on the client's requirements.
How can I achieve this? so that I just get the mapping details from the database and map them accordingly
I tried automapper ForMember method but I don't know how to pass the value from database?
CodePudding user response:
Let’s set up the scene, assuming you have the info for the client (A or B) in the Employee records.
DB Entity,
Employee:
FirstName,
LastName
Description,
Title,
ClientId
ViewModel,
EmployeeModel:
Name,
Title,
JobTitle
Create custom resolvers,
public class TitleResolver : IValueResolver<Employee, EmployeeModel, string>
{
public string Resolve(Employee source, EmployeeModel destination, string title, ResolutionContext context)
{
if(source.ClienId == "A") // as an example, you could do something different.
return source.Description;
return source.Title;
}
}
public class JobTitleResolver : IValueResolver<Employee, EmployeeModel, string>
{
public string Resolve(Employee source, EmployeeModel destination, string title, ResolutionContext context)
{
if(source.ClienId == "A")
return source.Title;
return source.Description;
}
}
When you configure the mapping,
var configuration =new MapperConfiguration(cfg => cfg.CreateMap<Employee, EmployeeModel>()
.ForMember(dest => dest.Title, opt => opt.MapFrom<TitleResolver>())
.ForMember(dest => dest.JobTitle, opt => opt.MapFrom<JobTitleResolver>()));
Let me know if this makes sense.
