Mapping the API results to DTOs

The entities definitions that we've used to work with EF Core are designed to give the best results when working with the database; however, they are not designed to be transferable over the wire. There are a few reasons why you wouldn't want to use the same classes that are mapped to your database tables and when sending results from your APIs:

  • Security: Your domain model classes might include various properties that you wouldn't want to expose to your clients. For example, personal information or user roles.
  • Loose coupling: Over time, you might need to change the data model; many times, these changes shouldn't be reflected in changes to your API, but sharing the same data types will force you to.
  • Controllable structure: The way entities are mapped to the database may include relationships that are not always simple for clients to use. Many times, it's easier for clients to work with a flattened structure.
  • Size: The API response goes over the wire, and therefore, we wish to make it as lean as possible for better performance.

There might be other reasons, but the conclusion should be the sameā€”don't use your data model entities in your APIs responses; instead, use a designated DTO.

DTOs are simple POCO classes that meet your API's purpose. For example, the ProductDTO class flattens the category and subcategory and includes just the name, while the City and Media items are included as DTOs:

public class ProductDTO
{
public int ProductId { get; set; }
public OwnerDTO Owner { get; set; }
public string Title { get; set; }
public string Description { get; set;
public string Category { get; set; }
public string Subcategory { get; set; }
public CityDTO City { get; set; }
public MediaDTO[] Media { get; set; }
}

Once you have the DTO definition in place, you'll need to write the code, the map, and the original entity into the DTO. However, writing mapping code is cumbersome (and boring), so instead, I'll teach how to make it automatic with AutoMapper.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.72.74