1
votes

I have two simple DTO defined that I'm passing to automapper v10.0.0

class RequestDTO {
   public int Id { get; set; }
   // other properties
   public IEnumerable<AssetDTO> Assets { get; set; }
}

class AssetDTO {
   public int RequestId { get; set; }
   // other properties
}

When I map an asset, it should show the RequestId. That's working fine. However, when I map a RequestDTO, there's no reason for each asset to include the RequestId as the Id is already included via the RequestDTO.

Is there a simple way to ignore the RequestId when it's being mapped as a result of the parent request being mapped?

So if I'm just mapping an asset, I want

{
  "RequestId": 12,
  "OtherProperty": ""
}

but if I'm mapping a request, I want:

{
  "Id": 12,
  "Assets": [
    {
      "OtherProperty", ""
    }
  ]
}
1

1 Answers

0
votes

It is nothing about mapping, but about the shape of the data object. AssetDTO is a class and it has the RequestId property defined. So, you cannot just expect to create an AssetDTO object and not have the RequestId property in it.

Even if you try to ignore it in the mapping process, you will end up having RequestId with a value of 0 (the default value for int type).

The main purpose of DTOs is to create data objects in different shapes as required, and it's fairly common to create a multitude of DTOs to map from a single Model type. Hence a solution to your problem would be using two different DTOs for mapping an Asset type in two different scenarios -

class ChildAssetDTO
{
    // other properties    // no RequestId in this class
}

class AssetDTO : ChildAssetDTO
{
    public int RequestId { get; set; }    // only the RequestId in this class
}

class RequestDTO
{
   public int Id { get; set; }
   // other properties
   public IEnumerable<ChildAssetDTO> Assets { get; set; }
}

Now you can use AssetDTO to map an Asset type, and AssetChildDTO to map a Request type.