0

I have a parent class: Item.
And a related, child class: Position.

I don't want to include Item as child of the Position class.
But when I use automapper, Item is always included as child of Position.

Classes:

// Item
  public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Position> Positions { get; set;}


// Position
  public int Id { get; set; }
  public int ItemId { get; set; }
  public int CoordinateX { get; set; }
  public int CoordinateY { get; set; }
  public Item Item { get; set; }


// Item DTO
  public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Position> Positions { get; set; }

// Mapping profile
   CreateMap<Item, ItemDTO>();

I get an Item like so:

Item item = dbContext.Items.AsNoTracking().Include(p => p.Positions);

It correctly returns the result. This is what I expect to see. Something like:

{
  Id: 1
  Name: "ABC",
  Positions:
    [
      {
        Id: 1,
        ItemId: 1,
        CoordinateX: 10,
        CoordinateY: 15,
        Item: []
      },
      {
        Id: 2,
        ItemId: 1,
        CoordinateX: 13,
        CoordinateY: 18,
        Item: []
      }
    ]
}

Note that the Item object in the children records is empty.
However, if I use automapper, Item is always included as child of Position.

var result = mapper.Map<ItemDTO>(item);

It produces the following result:

{
  Id: 1
  Name: "ABC",
  Positions:
    [
      {
        Id: 1,
        ItemId: 1,
        CoordinateX: 10,
        CoordinateY: 15,
        Item:
        [
          Id: 1,
          Name: "ABC",
          Positions: []
        ]
      },
      {
        Id: 2,
        ItemId: 1,
        CoordinateX: 13,
        CoordinateY: 18,
        Item:
        [
          Id: 1,
          Name: "ABC",
          Positions: []
        ]
      }
    ]
}

How can I use automapper and still achieve the expected result?
I'm using .NET 5 and automapper 8.1.1
I tried using the .Ignore property in the mapping profile, but the result was the same.

Krafter
  • 33
  • 2
  • 12

1 Answers1

1

You're not "mapping" the Position list, you're copying the reference.

I would create a PositionDTO as well, and configure the mapping from Position to PositionDTO to ignore the Item property. Otherwise you're still carrying references to the raw data object in your DTO, which is defeating the purpose of the DTO.

D Stanley
  • 149,601
  • 11
  • 178
  • 240