Use AutoMapper to dynamically map at runtime to different data types for same object [closed]

public class SweepstakeDTO : BaseDTO
{
    public required string Name { get; set; }

    public string? Description { get; set; } = string.Empty;

    public DateTimeOffset? StartDate { get; set; }

    public DateTimeOffset? EndDate { get; set; }

    public FullBusinessSummary? BusinessInfo { get; set; }

OR

    public FullBusinessDetails? BusinessInfo { get; set; }

}

.NET 8 – REST JSON – EFCore Code First

DTO objects are used to send/receive data to the client and EFCore Entities (Code First) are used to send/receive data to the SQL database. AutoMapper is used to map DTO->Entity and Entity->DTO. For most things, the DTO object is a replica of the Entity but we need to support custom responses. EFCore is loading the entity with all of the related (includes) data and then we use AutoMapper to only load the relevant data within the DTO object.

Depending on the client’s needs, sometimes we want a ‘detailed’ version of the entity (containing many/all? of the related data) vs. a ‘summary’ version (none/limited related data). This can be solved by creating 2 versions of the DTO object and letting AutoMapper fill the corresponding properties (most are named exactly the same so AutoMapper is doing the heavy lifting).

I am trying to avoid creating multiple versions of every DTO object. For example, the “BusinessDetail” or the “BusinessSummary” objects might be needed depending on the use case or a combination of other entities (e.g. BusinessDetail is needed but OrderSummary might be needed). I am trying to avoid creating mix-matches of DTOs for all of these use cases. I COULD use a dynamic or JSON as the object type to specify the correct object (e.g. type) at runtime but that does impact readability a bit but I believe I would lose the ability to have AutoMapper work by simply mapping only the available properties on the receiving object.

Any ideas?

  • 1

    Welcome to Stack Overflow. Please take the tour to learn how Stack Overflow works and read How to Ask on how to improve the quality of your question. Please see: Why is “Can someone help me?” not an actual question?. It is unclear what you are asking or what the problem is. Please edit you question to include a more detailed description of the specific problem you have.

    – 




Leave a Comment