GenericDtoSourceGenerator by Sergio Triana Escobedo
NuGet / site data
Details
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
Sergio Triana Escobedo

Original Readme
GenericDtoSourceGenerator
A powerful C# source generator that automatically generates Data Transfer Objects (DTOs) from your domain models at compile time.
Features
- 🚀 Zero Runtime Overhead: DTOs are generated at compile time using Roslyn source generators
- 🔄 Automatic Mapping: Generates
ToDto(),ToEntity(), andUpdateFrom()extension methods - 📦 Collection Support: Built-in support for mapping collections with
ToDtoList()andToEntityList() - 🎯 Flexible Configuration: Customize DTO names, namespaces, and property behavior
- ✅ Validation Ready: Optional
IValidatableObjectimplementation - 🔒 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.Jsonattributes 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
| Property | Type | Default | Description |
|---|---|---|---|
DtoName | string? | {ClassName}Dto | Name of the generated DTO |
Namespace | string? | {Namespace}.Dto | Namespace for the generated DTO |
UseRecord | bool | false | Generate a record instead of a class |
AccessModifier | string | "public" | Access modifier for the DTO |
GenerateParameterlessConstructor | bool | true | Generate parameterless constructor |
ImplementIEquatable | bool | false | Implement IEquatable<T> |
ImplementIValidatableObject | bool | false | Implement IValidatableObject |
AdditionalUsings | string[] | [] | Additional using statements |
IncludeInheritedProperties | bool | true | Include properties from base classes |
GenerateDocumentation | bool | true | Generate XML documentation comments |
GenerateMappers | bool | true | Generate mapping extension methods |
GenerateToDto | bool | true | Generate entity-to-DTO mapper |
GenerateToEntity | bool | true | Generate DTO-to-entity mapper |
GenerateUpdateFrom | bool | true | Generate entity update mapper |
GenerateCollectionMappers | bool | true | Generate list mapping helpers |
MapperNamespace | string? | DTO namespace | Namespace for mapper extension class |
MapperClassName | string? | {DtoName}MapperExtensions | Mapper extension class name |
GenerateToString | bool | true | Generate ToString() for class DTOs |
UseInitOnlyProperties | bool | false | Generate init accessors |
UseRequiredMembers | bool | false | Generate C# required for required reference properties |
GenerateJsonAttributes | bool | true | Emit configured System.Text.Json attributes |
######### [DtoProperty] Attribute
| Property | Type | Default | Description |
|---|---|---|---|
Name | string? | Property name | Custom name for the DTO property |
Ignore | bool | false | Exclude property from DTO |
Type | Type? | Original type | Custom type for the property |
DefaultValue | string? | None | Default value expression |
ForceNullable | NullableOption | Inherit | Force nullable/non-nullable |
Order | int | 0 | Property order in DTO |
Description | string? | Auto | Custom XML documentation |
MaxLength | int | -1 | Maximum length validation |
MinLength | int | -1 | Minimum length validation |
Pattern | string? | None | Regex pattern validation |
MinValue | double | double.MinValue | Minimum value for range |
MaxValue | double | double.MaxValue | Maximum value for range |
MapFrom | string? | Source property | Alternate source property for ToDto() |
MapTo | string? | Source property | Alternate entity property for reverse mapping |
ConverterType | Type? | None | Static converter type for custom mapping |
ConverterMethod | string? | None | Static converter method name |
IgnoreReverseMap | bool | false | Exclude property from ToEntity() and UpdateFrom() |
Flatten | bool | false | Allow a flattened MapFrom path such as Address.City |
Sensitive | bool | false | Exclude property from generated ToString() |
JsonIgnore | bool | false | Emit [JsonIgnore] |
JsonPropertyName | string? | None | Emit [JsonPropertyName] |
JsonConverterType | Type? | None | Emit [JsonConverter] |
######### [DtoIgnore] Attribute
Shorthand for [DtoProperty(Ignore = true)] - excludes the property from the generated DTO.
######### [DtoValidation] Attribute
| Property | Type | Description |
|---|---|---|
Required | bool | Adds [Required] validation |
EmailAddress | bool | Adds [EmailAddress] validation |
Phone | bool | Adds [Phone] validation |
Url | bool | Adds [Url] validation |
CreditCard | bool | Adds [CreditCard] validation |
ErrorMessage | string? | Custom error message |
CompareProperty | string? | Property to compare against |
CustomValidationType | Type? | Type used with [CustomValidation] |
CustomValidationMethod | string | Static 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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Acknowledgments
- Built with Roslyn Source Generators
- Inspired by modern DTO mapping patterns
About
Generating DTOs and mapping methods from domain models
How to use
Example (source csproj, source files)
- CSharp Project
- Person.cs
- Program.cs
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>
This is the use of GenericDtoSourceGenerator in Person.cs
using GenericDto.Core.Attributes;
namespace GenericDtoDemo;
[GenericDto]
public class Person
{
public string FirstName \{ get; set; \} = "";
public string LastName \{ get; set; \} = "";
}
This is the use of GenericDtoSourceGenerator in Program.cs
using GenericDtoDemo;
using GenericDtoDemo.Dto;
var person = new Person \{ FirstName = "Andrei", LastName = "Ignat" };
PersonDto dto = person.ToDto();
Console.WriteLine($"DTO: {dto.FirstName} {dto.LastName}");
Person restored = dto.ToEntity();
Console.WriteLine($"Person: {restored.FirstName} {restored.LastName}");
Generated Files
Those are taken from $(BaseIntermediateOutputPath)\GX
- GenericDtoAttributeMarker.g.cs
- GenericDtoDemo.Dto.PersonDto.g.cs
- GenericDtoDemo.Dto.PersonDtoMapper.g.cs
// <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 \{ }
}
// <auto-generated/>
// This code was generated by GenericDto Source Generator.
// Do not modify this file manually.
#nullable enable
using GenericDtoDemo;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace GenericDtoDemo.Dto
{
/// <summary>
/// DTO class generated from <see cref="GenericDtoDemo.Person"/>.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("GenericDto.Analyzers", "1.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
public partial class PersonDto
{
/// <summary>
/// Gets or sets the FirstName value.
/// </summary>
[global::System.ComponentModel.DataAnnotations.Required]
public string FirstName \{ get; set; \} = string.Empty;
/// <summary>
/// Gets or sets the LastName value.
/// </summary>
[global::System.ComponentModel.DataAnnotations.Required]
public string LastName \{ get; set; \} = string.Empty;
/// <summary>
/// Initializes a new instance of the <see cref="PersonDto"/> class.
/// </summary>
public PersonDto()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PersonDto"/> class with specified values.
/// </summary>
public PersonDto(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
/// <inheritdoc/>
public override string ToString()
{
return $"PersonDto {{ FirstName = {FirstName}, LastName = {LastName} }}";
}
}
}
// <auto-generated/>
// This code was generated by GenericDto Source Generator.
// Do not modify this file manually.
#nullable enable
using System;
using System.Collections.Generic;
using GenericDtoDemo;
namespace GenericDtoDemo.Dto
{
/// <summary>
/// Extension methods for mapping between <see cref="GenericDtoDemo.Person"/> and <see cref="PersonDto"/>.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("GenericDto.Analyzers", "1.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
public static class PersonDtoMapperExtensions
{
/// <summary>
/// Maps a <see cref="GenericDtoDemo.Person"/> instance to a new <see cref="PersonDto"/> instance.
/// </summary>
/// <param name="source">The source Person instance.</param>
/// <returns>A new PersonDto instance with mapped values.</returns>
public static PersonDto ToDto(this GenericDtoDemo.Person source)
{
if (source is null)
{
throw new global::System.ArgumentNullException(nameof(source));
}
return new PersonDto
{
FirstName = source.FirstName,
LastName = source.LastName,
};
}
/// <summary>
/// Maps a <see cref="PersonDto"/> instance to a new <see cref="GenericDtoDemo.Person"/> instance.
/// </summary>
/// <param name="dto">The source PersonDto instance.</param>
/// <returns>A new Person instance with mapped values.</returns>
public static GenericDtoDemo.Person ToEntity(this PersonDto dto)
{
if (dto is null)
{
throw new global::System.ArgumentNullException(nameof(dto));
}
return new GenericDtoDemo.Person
{
FirstName = dto.FirstName,
LastName = dto.LastName,
};
}
/// <summary>
/// Maps a collection of <see cref="GenericDtoDemo.Person"/> instances to a list of <see cref="PersonDto"/> instances.
/// </summary>
/// <param name="source">The source collection.</param>
/// <returns>A list of PersonDto instances with mapped values.</returns>
public static global::System.Collections.Generic.List<PersonDto> ToDtoList(this global::System.Collections.Generic.IEnumerable<GenericDtoDemo.Person> source)
{
if (source is null)
{
throw new global::System.ArgumentNullException(nameof(source));
}
var result = source is global::System.Collections.Generic.ICollection<GenericDtoDemo.Person> collection
? new global::System.Collections.Generic.List<PersonDto>(collection.Count)
: new global::System.Collections.Generic.List<PersonDto>();
foreach (var item in source)
{
result.Add(ToDto(item));
}
return result;
}
/// <summary>
/// Maps a collection of <see cref="PersonDto"/> instances to a list of <see cref="GenericDtoDemo.Person"/> instances.
/// </summary>
/// <param name="dtos">The source DTO collection.</param>
/// <returns>A list of Person instances with mapped values.</returns>
public static global::System.Collections.Generic.List<GenericDtoDemo.Person> ToEntityList(this global::System.Collections.Generic.IEnumerable<PersonDto> dtos)
{
if (dtos is null)
{
throw new global::System.ArgumentNullException(nameof(dtos));
}
var result = dtos is global::System.Collections.Generic.ICollection<PersonDto> collection
? new global::System.Collections.Generic.List<GenericDtoDemo.Person>(collection.Count)
: new global::System.Collections.Generic.List<GenericDtoDemo.Person>();
foreach (var dto in dtos)
{
result.Add(ToEntity(dto));
}
return result;
}
/// <summary>
/// Updates an existing <see cref="GenericDtoDemo.Person"/> instance with values from a <see cref="PersonDto"/>.
/// </summary>
/// <param name="entity">The entity to update.</param>
/// <param name="dto">The DTO containing the new values.</param>
/// <returns>The updated entity instance.</returns>
public static GenericDtoDemo.Person UpdateFrom(this GenericDtoDemo.Person entity, PersonDto dto)
{
if (entity is null)
{
throw new global::System.ArgumentNullException(nameof(entity));
}
if (dto is null)
{
throw new global::System.ArgumentNullException(nameof(dto));
}
entity.FirstName = dto.FirstName;
entity.LastName = dto.LastName;
return entity;
}
}
}
Useful
Download Example (.NET C#)
Share GenericDtoSourceGenerator
https://ignatandrei.github.io/RSCG_Examples/v2/docs/GenericDtoSourceGenerator
Category "Mapper" has the following generators:
1 AutoDTO
2023-08-24
2 AutoGen
2024-02-22
3 DapperFluentMap
2026-11-13
4 DevSource.ObjectMapping
2026-11-16
5 DotNetBrightener.Mapper
2026-11-14
6 DynamicsMapper
2023-10-16
7 Facet
2025-08-17
8 GenericDtoSourceGenerator
2026-11-24
9 LightweightObjectMapper
2024-09-18
10 lomapper
2026-04-07
11 MagicMap
2023-10-08
12 MapItEasy
2026-09-10
13 Mappa.Generator
2026-10-03
14 mapperly
2023-04-16
15 MapTo
2023-10-05
16 Najlot.Map.SourceGenerator
2026-08-29
17 NextGenMapper
2023-08-16
18 Synthetix
2026-11-18