I have a Question. I have 2 Dto Object and one Model.
What i'm trying todo is map the AssetDTO to the Asset Model using Automapper.
I have no clue on how to accomplish this.
public class AssetDTO
{
public string Code { get; set; }
public string CodeType { get; set; }
public List<MetricDataDTO> Data { get; set; }
}
public class MetricDataDTO
{
public string Value{ get; set; }
public string Flow { get; set; }
}
I have one model that look like this.
public class Asset
{
public string Code { get; set; }
public string CodeType { get; set; }
public string Value{ get; set; }
public string Flow { get; set; }
}
I tryed setting up the mapping with automapper but without any luck :( Hope anyone can help me out,Thanks in advance!!
CodePudding user response:
if suppose the value and flow inside asset is array, I think your current model for Asset
need to be change. Later you can check this one AutoMapper - Mapping list of objects to bigger list of objects .
In case for each asset there's only one value and flow, your model for AssetDTO
will become:
public class AssetDTO
{
public string Code { get; set; }
public string CodeType { get; set; }
public MetricDataDTO Data { get; set; }
}
And for such case, here the example for nested object (based on Using automapper for nested objects): https://dotnetfiddle.net/qVg59r
CodePudding user response:
Thanks to Lucian Bargaoanu!
If you need more control when flattening, you can use IncludeMembers. You can map members of a child object to the destination object when you already have a map from the child type to the destination type.
This allows you to reuse the configuration in the existing map for the child types MetricDataDTO when mapping the parent types AssetDTO and Asset .
It works in a similar way to mapping inheritance, but it uses composition, not inheritance.
cfg.CreateMap<AssetDTO, Asset>().IncludeMembers(s=>s.MetricDataDTO);
You can check this link for details. https://docs.automapper.org/en/latest/Flattening.html#includemembers
Hope it can help you.