Sunday, February 19, 2023

automapper map destination object to two sources objects

 problem:

i Have two models for child Components in blazor hosted app,

i need to bind two models to parent component model after validation for each one.


solution:

create map for two models with destination one

       
public class AutoMapper : Profile

    {

        public AutoMapper()

        {

  CreateMap();

        CreateMap();

} 

parent component declarations
       
[Inject] public IMapper? _mapper { get; set; }

 [Inject] protected IJSRuntime JS { get; set; }

[Inject] protected IWebAssemblyHostEnvironment host { get; set; }

 public ReceiptFormModel? FormModel { get; set; } = new();

  public VATTaxNumberModel? VATTaxNumberModel { get; set; }=new();

   public PolicyOwnerModel? PolicyOwnerModel { get; set; } =new();



 private async Task prepareModel()

        {

            var MapFirstModel = _mapper.Map(VATTaxNumberModel);

            FormModel= _mapper.Map(PolicyOwnerModel, MapFirstModel);



            LogToConsole($"FormModel=={JsonSerializer.Serialize(FormModel)}");

        }

protected void LogToConsole(string message)

    {

        if (host.IsDevelopment())

            JS.InvokeAsync("console.log", message);

    }