Skip to main content

GenericDtoSourceGenerator by Sergio Triana Escobedo

NuGet / site data​

Nuget GitHub last commit GitHub Repo stars

Details​

Info​

info

Name: GenericDtoSourceGenerator

Core attributes for GenericDto source generator - automatically generate DTOs from your domain models at compile time using Roslyn source generators.

Author: Sergio Triana Escobedo

NuGet: https://www.nuget.org/packages/BinaryCoffee.GenericDto/

You can find more details at https://github.com/stescobedo92/GenericDtoSourceGenerator

Source: https://github.com/stescobedo92/GenericDtoSourceGenerator

Author​

note

Sergio Triana Escobedo Alt text

Original Readme​

note

GenericDtoSourceGenerator​

A powerful C# source generator that automatically generates Data Transfer Objects (DTOs) from your domain models at compile time.

.NET License: GPL v3 CI Release

Features​
  • 🚀 Zero Runtime Overhead: DTOs are generated at compile time using Roslyn source generators
  • 🔄 Automatic Mapping: Generates ToDto(), ToEntity(), and UpdateFrom() extension methods
  • 📦 Collection Support: Built-in support for mapping collections with ToDtoList() and ToEntityList()
  • 🎯 Flexible Configuration: Customize DTO names, namespaces, and property behavior
  • ✅ Validation Ready: Optional IValidatableObject implementation
  • 🔒 Type Safe: Full nullable reference type support
  • 📝 Records Support: Generate record DTOs
  • 🧭 Scenario DTOs: Generate multiple DTOs from one source type
  • 🧩 Mapper Controls: Enable/disable mapper directions and customize mapper namespace/class names
  • 🧪 DataAnnotations and JSON: Generate validation and System.Text.Json attributes from DTO metadata
Installation​

######### NuGet Package

dotnet add package BinaryCoffee.GenericDto --version 1.0.1
Quick Start​

######### 1. Mark your entity with [GenericDto]

using GenericDto.Core.Attributes;

[GenericDto]
public class Customer
{
public int Id \{ get; set; }
public string Name \{ get; set; }
public string Email \{ get; set; }

[DtoIgnore]
public string InternalCode \{ get; set; \} // Won't appear in DTO
}

######### 2. Use the generated DTO and mappings

// A CustomerDto class is automatically generated in YourNamespace.Dto

var customer = new Customer \{ Id = 1, Name = "John", Email = "john@example.com" };

// Convert to DTO
var dto = customer.ToDto();

// Convert back to entity
var entity = dto.ToEntity();

// Update existing entity
existingCustomer.UpdateFrom(dto);

// Map collections
var dtos = customers.ToDtoList();
var entities = dtos.ToEntityList();
Configuration Options​

######### [GenericDto] Attribute

PropertyTypeDefaultDescription
DtoNamestring?{ClassName}DtoName of the generated DTO
Namespacestring?{Namespace}.DtoNamespace for the generated DTO
UseRecordboolfalseGenerate a record instead of a class
AccessModifierstring"public"Access modifier for the DTO
GenerateParameterlessConstructorbooltrueGenerate parameterless constructor
ImplementIEquatableboolfalseImplement IEquatable<T>
ImplementIValidatableObjectboolfalseImplement IValidatableObject
AdditionalUsingsstring[][]Additional using statements
IncludeInheritedPropertiesbooltrueInclude properties from base classes
GenerateDocumentationbooltrueGenerate XML documentation comments
GenerateMappersbooltrueGenerate mapping extension methods
GenerateToDtobooltrueGenerate entity-to-DTO mapper
GenerateToEntitybooltrueGenerate DTO-to-entity mapper
GenerateUpdateFrombooltrueGenerate entity update mapper
GenerateCollectionMappersbooltrueGenerate list mapping helpers
MapperNamespacestring?DTO namespaceNamespace for mapper extension class
MapperClassNamestring?{DtoName}MapperExtensionsMapper extension class name
GenerateToStringbooltrueGenerate ToString() for class DTOs
UseInitOnlyPropertiesboolfalseGenerate init accessors
UseRequiredMembersboolfalseGenerate C# required for required reference properties
GenerateJsonAttributesbooltrueEmit configured System.Text.Json attributes

######### [DtoProperty] Attribute

PropertyTypeDefaultDescription
Namestring?Property nameCustom name for the DTO property
IgnoreboolfalseExclude property from DTO
TypeType?Original typeCustom type for the property
DefaultValuestring?NoneDefault value expression
ForceNullableNullableOptionInheritForce nullable/non-nullable
Orderint0Property order in DTO
Descriptionstring?AutoCustom XML documentation
MaxLengthint-1Maximum length validation
MinLengthint-1Minimum length validation
Patternstring?NoneRegex pattern validation
MinValuedoubledouble.MinValueMinimum value for range
MaxValuedoubledouble.MaxValueMaximum value for range
MapFromstring?Source propertyAlternate source property for ToDto()
MapTostring?Source propertyAlternate entity property for reverse mapping
ConverterTypeType?NoneStatic converter type for custom mapping
ConverterMethodstring?NoneStatic converter method name
IgnoreReverseMapboolfalseExclude property from ToEntity() and UpdateFrom()
FlattenboolfalseAllow a flattened MapFrom path such as Address.City
SensitiveboolfalseExclude property from generated ToString()
JsonIgnoreboolfalseEmit [JsonIgnore]
JsonPropertyNamestring?NoneEmit [JsonPropertyName]
JsonConverterTypeType?NoneEmit [JsonConverter]

######### [DtoIgnore] Attribute

Shorthand for [DtoProperty(Ignore = true)] - excludes the property from the generated DTO.

######### [DtoValidation] Attribute

PropertyTypeDescription
RequiredboolAdds [Required] validation
EmailAddressboolAdds [EmailAddress] validation
PhoneboolAdds [Phone] validation
UrlboolAdds [Url] validation
CreditCardboolAdds [CreditCard] validation
ErrorMessagestring?Custom error message
ComparePropertystring?Property to compare against
CustomValidationTypeType?Type used with [CustomValidation]
CustomValidationMethodstringStatic method used with [CustomValidation]
Advanced Examples​

######### Using Records

[GenericDto(UseRecord = true)]
public class Product
{
public int Id \{ get; set; }
public string Name \{ get; set; }
public decimal Price \{ get; set; }
}

// Generates: public record ProductDto \{ ... }

######### Custom Namespace and Name

[GenericDto(
DtoName = "OrderResponse",
Namespace = "MyApi.Responses")]
public class Order
{
public Guid OrderId \{ get; set; }
public decimal TotalAmount \{ get; set; }
}

// Generates: MyApi.Responses.OrderResponse

######### With Validation

[GenericDto(ImplementIValidatableObject = true)]
public class User
{
public string Username \{ get; set; }

[DtoProperty(MaxLength = 100, MinLength = 5)]
public string Password \{ get; set; }

[DtoValidation(EmailAddress = true, Required = true)]
public string Email \{ get; set; }
}

######### Property Customization

[GenericDto]
public class Employee
{
public int Id \{ get; set; }

[DtoProperty(Name = "FullName")]
public string Name \{ get; set; }

[DtoProperty(DefaultValue = "DateTime.UtcNow")]
public DateTime HireDate \{ get; set; }

[DtoIgnore]
public decimal Salary \{ get; set; \} // Sensitive data excluded
}

######### Multiple DTOs From One Entity

[GenericDto(DtoName = "CustomerCreateDto", GenerateToEntity = false)]
[GenericDto(DtoName = "CustomerResponseDto")]
public class Customer
{
public int Id \{ get; set; }
public string Name \{ get; set; }
}

######### Custom Mapper Controls

[GenericDto(
MapperNamespace = "MyApi.Mapping",
MapperClassName = "CustomerMaps",
GenerateToEntity = false,
GenerateUpdateFrom = false)]
public class Customer
{
public int Id \{ get; set; }
}

######### JSON and Sensitive Properties

[GenericDto(UseInitOnlyProperties = true, UseRequiredMembers = true)]
public class Customer
{
[DtoProperty(JsonPropertyName = "full_name")]
public string Name \{ get; set; }

[DtoProperty(Sensitive = true, JsonIgnore = true)]
public string InternalToken \{ get; set; }
}
Generated Code​

For a class like:

[GenericDto]
public class Customer
{
public int Id \{ get; set; }
public string Name \{ get; set; }
}

The generator produces:

// CustomerDto.g.cs
namespace YourNamespace.Dto
{
public partial class CustomerDto
{
public int Id \{ get; set; }
public string Name \{ get; set; \} = string.Empty;

public CustomerDto() \{ }

public CustomerDto(int id, string name)
{
Id = id;
Name = name;
}
}
}

// CustomerDtoMapper.g.cs
namespace YourNamespace.Dto
{
public static class CustomerDtoMapperExtensions
{
public static CustomerDto ToDto(this Customer source) \{ ... }
public static Customer ToEntity(this CustomerDto dto) \{ ... }
public static List<CustomerDto> ToDtoList(this IEnumerable<Customer> source) \{ ... }
public static Customer UpdateFrom(this Customer entity, CustomerDto dto) \{ ... }
}
}
Requirements​
  • .NET 10.0+ (for the example project)
  • .NET Standard 2.0 compatible (for the analyzers and core attributes)
  • Visual Studio 2022 or later / Rider / VS Code with C# extension
License​

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.

Contributing​

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request
Acknowledgments​
  • Built with Roslyn Source Generators
  • Inspired by modern DTO mapping patterns

About​

note

Generating DTOs and mapping methods from domain models

How to use​

Example (source csproj, source files)​

This is the CSharp Project that references GenericDtoSourceGenerator

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BinaryCoffee.GenericDto" Version="1.1.1" />
</ItemGroup>
</Project>

Generated Files​

Those are taken from $(BaseIntermediateOutputPath)\GX

// <auto-generated/>
// This file was generated by GenericDto Source Generator

[assembly: GenericDto.Analyzers.GenericDtoGeneratedAttribute]

namespace GenericDto.Analyzers
{
[global::System.AttributeUsage(global::System.AttributeTargets.Assembly)]
internal sealed class GenericDtoGeneratedAttribute : global::System.Attribute \{ }
}

Useful​

Download Example (.NET C#)​

Share GenericDtoSourceGenerator​

https://ignatandrei.github.io/RSCG_Examples/v2/docs/GenericDtoSourceGenerator

Category "Mapper" has the following generators:​

1 AutoDTO Nuget GitHub Repo stars 2023-08-24

2 AutoGen Nuget GitHub Repo stars 2024-02-22

3 DapperFluentMap Nuget GitHub Repo stars 2026-11-13

4 DevSource.ObjectMapping Nuget GitHub Repo stars 2026-11-16

5 DotNetBrightener.Mapper Nuget GitHub Repo stars 2026-11-14

6 DynamicsMapper Nuget GitHub Repo stars 2023-10-16

7 Facet Nuget GitHub Repo stars 2025-08-17

8 GenericDtoSourceGenerator Nuget GitHub Repo stars 2026-11-24

9 LightweightObjectMapper Nuget GitHub Repo stars 2024-09-18

10 lomapper Nuget GitHub Repo stars 2026-04-07

11 MagicMap Nuget GitHub Repo stars 2023-10-08

12 MapItEasy Nuget GitHub Repo stars 2026-09-10

13 Mappa.Generator Nuget GitHub Repo stars 2026-10-03

14 mapperly Nuget GitHub Repo stars 2023-04-16

15 MapTo Nuget GitHub Repo stars 2023-10-05

16 Najlot.Map.SourceGenerator Nuget GitHub Repo stars 2026-08-29

17 NextGenMapper Nuget GitHub Repo stars 2023-08-16

18 Synthetix Nuget GitHub Repo stars 2026-11-18

See category​

Mapper