Skip to content

Automatic DTO mapping #21242

Closed
Closed
@hillin

Description

@hillin

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

In ABP we have to create AutoMapper mappings for a domain type and its corresponding DTO type. In multiple projects we developed, we found that most of the time we don't need to configure custom mapping rules for these types, they are basically one-to-one projections. To reduce boilerplate, we developed a method which automatically create these kind of mappings.

Describe the solution you'd like

The idea is to add an attribute DtoAttribute:

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class DtoAttribute(
    DtoMappingDirection mappingDirection = DtoMappingDirection.SourceToDto)
    : Attribute
{
    public DtoMappingDirection MappingDirection => mappingDirection;
    public string? SourceTypeName { get; set; }
}

public enum DtoMappingDirection
{
    SourceToDto,
    DtoToSource,
    Bidirectional
}

Any DTO class in the application contracts layer could be decorated with this attribute. In the application layer, automatically scan for types with this attribute in the contracts assembly, create mappings accordingly:

  • mappingDirection determines the mapping direction, as the enum suggests;
  • SourceTypeName could be specified or inferred by removing the Dto suffix of the DTO class. The source type is looked up from the domain assembly.

We can extend the rules a bit, such as if a type with [Dto] has a name ends with Input, automatically create a DTO-to-source mapping etc., but I'm not sure if it's necessary.

Additional context

I'd be happy to submit a PR for this feature.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions