Skip to content

Nextended.CodeGen ​

📚 Full API reference — every public type and member, generated from the compiled assembly.

🇩🇪 Diese Seite auf Deutsch

Compile-time source code generation from various sources including classes, JSON, XML, and Excel files.

Overview ​

Nextended.CodeGen is a Roslyn source generator that automatically generates code at compile-time. It supports DTO generation from attributes, class generation from JSON/XML structures, model generation from Excel spreadsheets, and TypeScript declarations of your contracts. All generators are configured with a fluent configuration class (recommended), with attributes, with codegen.json, or any mix of them.

Note: This package is in early testing stage. The API may change in future releases.

Installation ​

bash
dotnet add package Nextended.CodeGen
dotnet add package Nextended.Core

Fluent configuration ​

The recommended way to configure the generators. Instead of attributes on your entities and a codegen.json, one or more configuration classes describe what is generated — like a ResponseFilter<T> or a FluentValidation validator. Attributes and codegen.json keep working unchanged; the fluent configuration refines them, and with it codegen.json becomes optional.

csharp
using Nextended.Core.CodeGen;
using Nextended.Core.Enums;

// the DTOs of one entity
public sealed class ProductDtoConfig : DtoConfig<Product>
{
    public ProductDtoConfig()
    {
        Ignore(x => x.InternalNote);
        Property(x => x.Sku).PropertyName("ArticleNumber");
        MappingStrategy(DtoMappingStrategy.Mapperly);

        // a second DTO of the same entity (a view, see "DTO views" below)
        View("ProductRow", v => v
            .Ignore(x => x.Category, x => x.Tags)
            .BaseMembersFirst()
            .Order(x => x.Name, x => x.Price)
            .ToDtoMethodName("ToRow"));
    }
}

// the whole project: what codegen.json would hold, the types to generate, rules for groups of types
public sealed class AppCodeGen : CodeGenConfig
{
    public AppCodeGen()
    {
        Defaults(d => d
            .Namespace("MyApp.Contracts")
            .OutputPath("./Generated/Dtos/")
            .InitializeCollections()
            .DefaultMappingSettings(m => m.Strategy(DtoMappingStrategy.Mapperly)));

        Dto<Entity>(e => e.Ignore(x => x.TenantId));          // reaches every DTO and view of every entity
        Dto<Category>();                                       // no [AutoGenerateDto] needed
        Dto(typeof(Page<>), p => p.Suffix("Model"));           // open generic types through typeof
        IgnoreType<LegacyImport>();
        ForNamespace("MyApp.Domain.Codes", n => n.Namespace("MyApp.Contracts.Codes"));
        ForAssembly("MyApp.Admin", a => a.Defaults(d => d.Namespace("MyApp.Admin.Contracts")));
    }
}

The classes are found automatically (every class deriving from CodeGenConfig or DtoConfig<T> in the project, in any namespace, also partial). They are read by the generator at compile time, never executed — see What you can write.

Requirements: a Nextended.Core that contains Nextended.Core.CodeGen (the API types) and a Nextended.CodeGen that reads them. Without codegen.json, relative paths (OutputPath, SourceFile) resolve against the project directory. Runnable: CodeGenFluentSample (no attribute, no json), edge cases in FluentConfigTests, design and rationale in Fluent configuration — design.

Precedence ​

LevelSourceWins over
1codegen.json (DtoGeneration)—
2fluent Defaults(...)the json values (they stay defaults: an attribute still wins over them)
3[AutoGenerateDto], [GenerationPropertySetting], [IgnoreOnGeneration]defaults
4fluent ForNamespace(...) (shorter namespace first)attributes
5fluent Dto<T>(...) / DtoConfig<T>everything above

Several configuration classes are merged in the order of their full type names. Two classes that set the same setting of the same DTO to different values get NCG022; the later one wins. Within one class later calls win, as in normal code.

Names: everything you know, as a method ​

Every setting is a method named exactly like the attribute or json property it mirrors; a bool setting takes an optional true (InitializeCollections() = InitializeCollections(true)):

BuilderSettingsOperations
Defaults(d => ...)every DtoGeneration setting of codegen.json (Namespace, OutputPath, PropertiesToIgnore, TypesToIgnore, DeepProperties, ...), DefaultMappingSettings(m => ...)Emit(...) for every DTO
Dto<T>(d => ...), DtoConfig<T>, Dto(typeof(...), ...), ForNamespace(...)every [AutoGenerateDto] property (Namespace, Suffix, GeneratedClassName, MappingStrategy, PreClassString, UseViews, OutputPath, ...)Ignore(...), Include(...), Property(...), Property(..., p => ...), Order(...), OrderLast(...), BaseMembersFirst(), Emit(...), View(name, v => ...) (not in ForNamespace), Facet(x => ..., f => ...) (only Dto<T>/DtoConfig<T>)
ViewDefaults(v => ...)the same settings, for every viewIgnore(...), Include(...), Property(...), Order(...), OrderLast(...), BaseMembersFirst(), Emit(...) — by name, see Views
Property(x => x.Member)every [GenerationPropertySetting] property (PropertyName, PreClassString, PreInterfaceString, MapWithClassMapper, InterfaceAccess, ...)Ignore(), Include()
Facets<T>(f => f.Facet(x => x.Member, o => ...)), Facet(...)every [ProvideFacet] property (Label, Type, MultiSelect, GroupOperator, Order, TopDistinct, ValuePath, LabelPath, ValueType/ValueType<T>())— see Facets
Typescript(t => ...)every setting of a Typescript entry; Include<T>(), IncludeDerivedFrom<T>(), Exclude<T>(), TypeMap(...)Type<T>(x => ...): Name, Ignore, Property(...).Name/Type/Optional/Ignore/Include; DtoConfig<T>.Typescript(...) per type — see TypeScript generation
ExcelGeneration(e => ...), StructureGeneration(s => ...)every setting of an ExcelGenerations / StructureGenerations entry; ColumnMapping(header, property), PropertyTypeOverride(property, type)—

PropertiesToIgnore and PropertyNames of the attribute have no method of their own: Ignore(...) and Property(...).PropertyName(...) do the same, per DTO.

Three short aliases exist for the longest names (the originals stay): Name("B") = PropertyName("B") on a member, Attribute("[X]") / Attributes("[X]", "[Y]") = PreClassString(...) on a member or a DTO, KeepAttributes() = KeepAttributesOnGeneratedClass() on a member or a DTO:

csharp
Property(x => x.Sku).Name("ArticleNumber").Attribute("[JsonPropertyOrder(1)]");

Attribute<TAttribute>(args) writes an attribute from its type instead of a string: the generator takes the full name from the symbol (global::, namespace and containing types, the Attribute suffix dropped like kept attributes) and writes the arguments as C# literals. A rename of the attribute or of a constant reaches the generated code, a typo is a compile error in the configuration:

csharp
Property(x => x.LoadingPort).Attribute<FacetDisplayAttribute>(Displays.Port);   // [global::My.Ui.FacetDisplay("port")]
Property(x => x.OriginCountry).Attribute<CountryCodeAttribute>();               // [global::My.Ui.CountryCode]
Property(x => x.Total).Attribute<RangeAttribute>(0, 1000.5);                    // [global::System.ComponentModel.DataAnnotations.Range(0, 1000.5D)]
Attribute<KnownTypeAttribute>(typeof(Order));                                   // on the DTO: [global::System.Runtime.Serialization.KnownType(typeof(global::Shop.Order))]
Property(x => x.State).Attribute<MarkAttribute>(a => { a.Label = nameof(Order.State); a.Tone = Tone.Loud; }, 1);
                                                                                // [global::Lib.Mark(1, Label = "State", Tone = global::Lib.Tone.Loud)]
ArgumentWritten as
string, charescaped literal: "a\"b", 'c' (const, nameof and constant interpolated strings included)
bool, int, nulltrue, 1, null
long, uint, ulong, float, doublewith suffix: 1L, 1U, 1UL, 1.5F, 2.5D
byte, sbyte, short, ushortwith cast: ((byte)7)
enumglobal::Ns.Tone.Loud; a value without a member ((global::Ns.Tone)5)
typeof(X)typeof(global::Ns.X), open generics as typeof(global::Ns.Box<>)
arraynew int[] { 1, 2 }, empty new string[0]

Generic attributes (Attribute<TypedAttribute<int>>() → [global::Ns.Typed<int>]) and nested ones (Holder.InnerAttribute → [global::Ns.Holder.Inner(...)]) work. Named arguments go in the lambda a => a.Name = value (properties and fields of the attribute, constants only); the constructor arguments follow it. The arguments are not checked against the attribute's constructors: a wrong argument is a compile error in the generated file. Anything that is not constant (static readonly fields, method calls) is reported (NCG020) and the statement is skipped. It exists everywhere Attribute(string) does: Dto<T>, DtoConfig<T>, Dto(typeof(...)), ForNamespace, ViewDefaults, views and Property(...).

Typed attributes add up in call order; the same attribute twice is written once. Attribute(string), Attributes(...) and PreClassString(...) keep their behaviour: they set the text and replace what was there (the last one wins). So a string first and typed attributes after it combine, a string after typed attributes replaces them:

csharp
Property(x => x.Port).Attribute<FacetDisplayAttribute>(Displays.Port).Attribute<CountryCodeAttribute>();
                                     // [global::My.Ui.FacetDisplay("port")] [global::My.Ui.CountryCode]
Property(x => x.Code).Attribute("[JsonPropertyOrder(1)]").Attribute<CountryCodeAttribute>();
                                     // [JsonPropertyOrder(1)] [global::My.Ui.CountryCode]
Property(x => x.Name).Attribute<CountryCodeAttribute>().Attribute("[JsonPropertyOrder(1)]");
                                     // [JsonPropertyOrder(1)]   (the string replaces)

Typed attributes of several configuration classes add up too (in the order of their full names); strings of several classes still report NCG022 when they differ.

The other settings that name a type have typed forms as well, rendered the same way (full name with global:: from the symbol, type arguments too); the string forms stay as they are:

String formTyped formsWhere
BaseType("Volo.Abp.Application.Dtos.IEntityDto<Guid>")BaseType<IEntityDto<Guid>>(), BaseType(typeof(IEntityDto<Guid>)) → global::Volo.Abp.Application.Dtos.IEntityDto<global::System.Guid>Defaults, Dto<T>, DtoConfig<T>, Dto(typeof), ForNamespace, ViewDefaults, views
Interfaces("A", "B") (replaces the list)Interface<IA>(), Interface(typeof(IA)) (add to the list, the same one once)the same
PropertyTypeOverride("Total", "decimal")PropertyTypeOverride<decimal>("Total"), PropertyTypeOverride("Total", typeof(decimal))ExcelGeneration
TypesToIgnore("X")IgnoreType<X>(), IgnoreType(typeof(X)) (existed before)root (CodeGenConfig)

An open generic type (BaseType(typeof(EntityDto<>))) is written with its type parameter names (global::Ns.EntityDto<TKey>), so it fits a generic DTO with parameters of those names. BaseType(null) now needs a cast, BaseType((string?)null) (two overloads take null); null still means "the default". Settings that name namespaces, files, members or TypeScript types (Namespace, Usings, UseViews, OutputPath, TypeScript Type("...")) have no typed form; TypeScript's type selections (Include<T>(), IncludeDerivedFrom<T>(), TypeMap<T>(...), DerivedType<T>(), IncludeMembersWithAttribute<T>(), IncludeTypesWithAttribute<T>()) were typed already.

Members ​

  • Ignore(x => x.A, x => x.B) leaves members out, Include(...) takes members in again that [IgnoreOnGeneration], PropertiesToIgnore or the json PropertiesToIgnore leave out. The string forms (Ignore("A"), Property("A")) work for enum members and for names in ForNamespace; an unknown name is reported (NCG021).

  • A member rule on a type applies to its default DTO and its views (like an attribute on the property), unless the view has a rule of its own. It also applies to the DTOs of derived types: Dto<Entity>(e => e.Ignore(x => x.TenantId)) removes TenantId from every entity DTO and every view.

  • The more specific rule wins. Lookup order for a member: the view → the type → its base types → ForNamespace rules; the nearest rule decides. So one entity, or one view, takes a member in again that a base type leaves out:

    csharp
    Dto<Entity>(e => e.Ignore(x => x.TenantId));                        // all entity DTOs and views ...
    Dto<Currency>(c => c.Include(x => x.TenantId));                     // ... but CurrencyDto (and its views) carry it
    Dto<Country>(c => c.View("CountryAdmin", v => v.Include(x => x.TenantId)));   // ... and the CountryAdmin view

    CurrencyDto then declares TenantId itself (the base DTO still leaves it out).

  • Contrast with the attribute: PropertiesToIgnore of an [AutoGenerateDto] stays per DTO, as it always was (a list on a base type's attribute reaches only the base DTO) — kept for backward compatibility. [IgnoreOnGeneration] on the property reaches every DTO, like a fluent rule on the base, and a fluent Include on a more specific type or view undoes either.

  • A rule on a derived type for an inherited member reaches the derived type's views (they are flat), but not its default DTO: there the member lives in the base DTO. This is reported (NCG023); configure it on the base type instead.

  • Order(x => x.Name, x => x.Price) puts these members first, in this order; OrderLast(x => x.CreationTime, x => x.Id) puts these members last, in this order (both name the source members, also when Property(...).Name(...) renames them); BaseMembersFirst() lists inherited members before the own ones. They combine: BaseMembersFirst sorts by depth, then the Order members go first and the OrderLast members last, everything else keeps its place. The generated class lists its members in that order, so a flat DTO (a view, or a DTO with DeepProperties) is serialized in that order — an existing JSON order needs no [JsonPropertyOrder] lists. (A default DTO with a base DTO orders its own members; the base DTO's members belong to the base DTO.)

  • "Its place" is the declaration order, and it is the same in every build. A type declared in several files (partial) lists its members by file — the files of a folder before its subfolders, by name ignoring case, like the default Compile glob — then by position in the file. The order the build hands the files to the compiler (Visual Studio, the command line, an incremental build) no longer matters; before 10.1.63 a member of another partial file could move from last to first between builds. A type in one file keeps its order. The same applies to the TypeScript generation and to the generated mappers.

  • Property(x => x.Number, p => p.Name("No")) does what Property(x => x.Number).Name("No") does but returns the DTO builder, so a chain goes on: d.Property(x => x.A, p => p.Name("B")).Ignore(x => x.C). The string form exists too: Property("A", p => ...).

Types ​

  • Dto<T>(...) only refines: everything T already gets stays — the settings of its own [AutoGenerateDto], or of the base's attribute when it comes in through AutoGenerateDerived, the json defaults and the ForNamespace rules — and only what the call sets is overridden. Dto<Currency>(c => c.Suffix("Model")) on a Currency that gets its DTO from [AutoGenerateDto(AutoGenerateDerived = true, Namespace = "Shop.Codes")] on its base keeps that namespace and the base's ignores, it only changes the suffix.
  • Dto<T>() on a type that gets no DTO at all (no attribute, not derived from a generated type) opts it in, with the defaults.
  • Dto(typeof(Box<>), ...) configures an open generic type; Dto<Box<int>>(...) configures the same Box<T> (any construction does). Both can define views: Dto(typeof(Box<>), b => b.View("BoxRef", v => v.Ignore("Label"))) with member names, or Dto<Box<int>>(b => b.View("BoxRef", v => v.Ignore(x => x.Label))) with selectors — either way the view is BoxRefDto<T>.
  • IgnoreType<T>() / IgnoreType(typeof(T)) leaves a type out even when it has [AutoGenerateDto], together with the types that come in only through its AutoGenerateDerived.
  • AutoGenerateDerived() set fluently takes the derived types in, as the attribute property does.
  • Enums: Dto<State>(s => s.Ignore(nameof(State.Legacy)).PreClassString("[JsonConverter(typeof(JsonStringEnumConverter))]")).

Views ​

View(name, v => ...) is a further [AutoGenerateDto] with GeneratedClassName = name: the same flat DTO with its own settings and mapping (see DTO views). A fluent view with the name of an attribute view refines that view. The view's name is its GeneratedClassName (setting it inside the view is reported).

What a view leaves out. A view starts from the defaults like every DTO, json/fluent PropertiesToIgnore included. Its Ignore(...)adds to that list (Include(...) takes a member of it in again). A PropertiesToIgnore on a view's [AutoGenerateDto] instead replaces the default list (as it does on every attribute). So when moving a view from attributes to the fluent configuration, list only what the view leaves out beyond the defaults:

csharp
// defaults: PropertiesToIgnore("TenantId", "CreatedBy")
[AutoGenerateDto(GeneratedClassName = "PortRef", PropertiesToIgnore = ["TenantId", "CreatedBy", "Country"])]   // the whole list
Dto<Port>(d => d.View("PortRef", v => v.Ignore(x => x.Country)));                                         // only the extra member

Defaults for every view. ViewDefaults(v => ...) holds settings and member rules (by name) that every view gets — attribute views and fluent views, of every type — instead of repeating them on each view:

csharp
ViewDefaults(v => v
    .Namespace("MyApp.Contracts.Views")
    .OutputPath("../MyApp.Contracts/Generated/Views/")
    .Ignore("DateCreatedUtc", "DateUpdatedUtc")
    .Order("Id"));

Dto<Port>(d => d.View("PortRef", v => v.Ignore(x => x.Country)));            // gets all of the above
Dto<Offer>(d => d.View("Offer", v => v
    .Include(x => x.DateCreatedUtc)                                         // the view's own rule wins
    .Property(x => x.DateCreatedUtc, p => p.Name("CreationTime"))
    .OrderLast(x => x.DateCreatedUtc)));                                    // member names are the source names

What a view sets itself wins: its View(...) settings, the properties its [AutoGenerateDto] sets (Namespace = "X" on the attribute beats the default), and member rules on the view or on its type (Dto<Offer>(d => d.Include(...))); the defaults' member rules are looked up last. Default DTOs are not affected. ViewDefaults cannot define views (NCG020); Defaults(d => d.Emit(...)) already covers every DTO, ViewDefaults(v => v.Emit(...)) only the views. Without ViewDefaults nothing changes.

Additional files (Emit) ​

Emit(fileName, template, outputPath = null) writes one more file per DTO from a template — on a type (its default DTO), on a view, in ForNamespace, or in Defaults (every DTO, views included):

csharp
Defaults(d => d.Emit("{Dto}.Json.g.cs", """
    namespace {DtoNamespace};

    [System.Text.Json.Serialization.JsonSerializable(typeof({Dto}))]
    public partial class {Dto}JsonContext : System.Text.Json.Serialization.JsonSerializerContext;
    """));

Placeholders in file name and template: {Dto}, {Interface}, {DtoNamespace}, {DtoFullName}, {Source}, {SourceNamespace}, {SourceFullName}, {View}. The file goes where the DTO goes (OutputPath of the DTO, else of the configuration, else the compilation); outputPath overrides it. A file that is not .cs needs a path on disk, and two DTOs may not write the same file (NCG024).

Facets ​

Nextended.Core.Facets.FacetBuilder builds filter facets from [ProvideFacet] on the properties of a type. For types that cannot carry the attribute — a model copied from another team, a referenced assembly, or simply clean entities — the facets go into the configuration:

csharp
Facets<CalculatedShipment>(f => f
    .Facet(x => x.ActualDeliveryDate, o => o.Label("Actual delivery").Type(FacetType.DateRange))
    .Facet(x => x.ConsigneeName, o => o.Label("Consignee name")));

Facets<ShipmentBase>(f => f                                                 // reaches Shipment and every other derived type
    .Facet(x => x.EstimatedArrival, o => o.Label("Estimated arrival").Type(FacetType.DateRange).MultiSelect(false)
        .GroupOperator(FacetGroupOperator.And).Order(40))
    .Facet(x => x.PortOfLoading, o => o.Label("Port of loading").ValuePath("PortOfLoading.Id").LabelPath("PortOfLoading.Name")
        .ValueType<Guid>()));

// in a DtoConfig<T>, or inside Dto<T>(d => ...):
Facet(x => x.State, o => o.Label("State").Order(10));

The settings are named exactly like the properties of [ProvideFacet] (Label, Type, MultiSelect, GroupOperator, Order, TopDistinct, ValuePath, LabelPath, ValueType(typeof(...)) / ValueType<T>()); Facet(x => x.A) alone is [ProvideFacet] with its defaults. Facets<T> gives the type no DTO; Facet inside Dto<T>/DtoConfig<T> belongs to a type that has one anyway.

How it reaches the facet builder: the facet builder reads the facets by reflection at run time, so the generator writes the rules as code — a module initializer (NextendedFacetRegistrations.g.cs, compiled into the project, nothing on disk) that calls FacetRegistry.Register(typeof(CalculatedShipment), "ActualDeliveryDate", f => { f.Label = ...; }). FacetBuilder and FacetRegistry.GetFacets(type) / FacetRegistry.GetFacet(type, property) merge the registrations with the attributes:

  • a property with [ProvideFacet] keeps it; the fluent values override the attribute's values, the others stay (attribute, then fluent);
  • a registration on a base type reaches the derived types; a nearer registration wins;
  • a registration on a generic type (Facets<Box<int>>) covers every construction of Box<T>.

FacetRegistry runs the module initializers of the type's assemblies before it reads, so the registrations are there even when no other code of the assembly ran yet — as long as the configuration lives in the assembly of the type or of one of its base types (the usual place). A configuration in another assembly registers when that assembly's code first runs. Code that reads [ProvideFacet] itself should read FacetRegistry.GetFacets(type) instead to see both. FacetRegistry.Register(...) can also be called directly (tests, facets computed at run time).

Needs .NET 5 or later (module initializers) and a Nextended.Core with FacetRegistry; otherwise the rules are reported (NCG027) and not registered.

Per namespace and per assembly ​

  • ForNamespace("MyApp.Domain.Codes", n => ...): type settings and member rules (by name) for every generated type in that namespace or below it.
  • ForAssembly("MyApp.Admin", a => ...): rules (the same language as the class itself) that apply only when the generating project's assembly has that name — for a configuration file shared by several projects. Rules for other assemblies are still checked.

What you can write ​

The constructor body is analysed, not run. Allowed: calls of the Nextended.Core.CodeGen API (chained or as statements), constants of any kind ("x", const fields, nameof, enum members, constant interpolated and raw strings), typeof, member selectors on the lambda parameter (x => x.Member), nested lambdas, arrays and collection expressions of constants. Everything else is an error on the exact expression, and the statement is skipped:

csharp
var suffix = "Dto";                         // NCG020: a statement that is not a call
Dto<Order>(o => o.Suffix(suffix));          // NCG020: not a constant
Dto<Order>(o => o.Ignore(x => x.A.B));      // NCG020: selectors select one member of the parameter
if (useViews) View("Row");                  // NCG020: no control flow
IdSeverityWhen
NCG020erroran expression the generator cannot read; the statement is skipped
NCG021warninga member name the type does not have
NCG022warningtwo configuration classes set the same setting to different values (the later full name wins)
NCG023warninga rule on a derived type for an inherited member: no effect on the default DTO
NCG024errorEmit without output path for a non-.cs file, or two DTOs emit the same file
NCG025warningDto<T> for a type that cannot get a DTO (struct, interface, static class)
NCG026warninga call this Nextended.CodeGen does not know (a newer Nextended.Core); update Nextended.CodeGen
NCG027warningFacet(...) rules in a project without module initializers (before .NET 5) or with a Nextended.Core without FacetRegistry

Attributes and fluent side by side ​

Attributes / jsonFluent
[AutoGenerateDto] on OrderDto<Order>() or class OrderDtoConfig : DtoConfig<Order>
[AutoGenerateDto(Namespace = "X", Suffix = "Model")]Dto<Order>(o => o.Namespace("X").Suffix("Model"))
[IgnoreOnGeneration] on Order.NoteDto<Order>(o => o.Ignore(x => x.Note))
[GenerationPropertySetting(PropertyName = "No")]Property(x => x.Number).PropertyName("No")
[GenerationPropertySetting(View = "Row", PropertyName = "No")]View("Row", v => v.Property(x => x.Number).PropertyName("No"))
further [AutoGenerateDto(GeneratedClassName = "Row", PropertiesToIgnore = ["Lines"])]View("Row", v => v.Ignore(x => x.Lines)) (the attribute's list replaces the default PropertiesToIgnore, Ignore adds to it)
the same settings on every viewViewDefaults(v => v.Namespace("X").OutputPath("Views/"))
[JsonPropertyOrder(-1)] / [JsonPropertyOrder(1)] on view membersView("Row", v => v.Order(x => x.Id).OrderLast(x => x.CreationTime))
[ProvideFacet(Label = "ETA", Type = FacetType.DateRange)] on Shipment.EtaFacets<Shipment>(f => f.Facet(x => x.Eta, o => o.Label("ETA").Type(FacetType.DateRange)))
"DtoGeneration": { "DeleteStaleFiles": true }Defaults(d => d.DeleteStaleFiles())
"TypesToIgnore": ["Legacy"]IgnoreType<Legacy>()
"DtoGeneration": { "Namespace": "X", "InitializeCollections": true }Defaults(d => d.Namespace("X").InitializeCollections())
"ExcelGenerations": [{ "SourceFile": "a.xlsx", ... }]ExcelGeneration(e => e.SourceFile("a.xlsx")...)

The test Fluent_configuration_generates_the_same_files_as_the_equivalent_attributes proves that both columns generate the same files.

TypeScript generation ​

TypeScript declarations of your C# contracts — DTOs, enums, OData rows, SignalR payloads — that follow what the server's JSON serializer really writes. Typical use: the types OpenAPI does not describe (OData sets, SignalR messages, client-side rows) and frontends that keep hand-written src/types/*.ts today.

Off by default. Nothing happens without a TypeScript generation with an OutputPath; the attributes alone do nothing, a missing section never breaks a build, and TypeScript is never added to the compilation (it is written to disk, like OutputPath DTOs).

csharp
using Nextended.Core.CodeGen;
using Nextended.Core.Enums;

public sealed class AppCodeGen : CodeGenConfig
{
    public AppCodeGen()
    {
        Typescript(t => t
            .OutputPath("../frontend/src/types/generated")      // relative to the project (or the json file)
            .EnumValues(TypescriptEnumValues.Number)            // enums as numbers (the default; String = names)
            .IncludeNamespaces("MyApp.Contracts")               // what to generate (see "Which types")
            .RootNamespace("MyApp.Contracts")                   // left out of the folders
            .TypeMap(typeof(PagedResultDto<>), "PagedResult from '../abp'")
            .Type<ShipmentDto>(s => s
                .Name("ApiShipment")
                .Ignore(x => x.InternalNote)
                .Property(x => x.Discriminator).Type("'Pickup' | 'Consol' | 'Delivery'")));
    }
}

The same in codegen.json (an entry of the Typescript list; the settings are named exactly like the fluent methods):

json
{
  "Typescript": [
    {
      "OutputPath": "../frontend/src/types/generated",
      "EnumValues": "Number",
      "IncludeNamespaces": [ "MyApp.Contracts" ],
      "RootNamespace": "MyApp.Contracts",
      "TypeMap": { "Volo.Abp.Application.Dtos.PagedResultDto<T>": "PagedResult from '../abp'" },
      "Types": {
        "MyApp.Contracts.ShipmentDto": {
          "Name": "ApiShipment",
          "Members": {
            "InternalNote": { "Ignore": true },
            "Discriminator": { "Type": "'Pickup' | 'Consol' | 'Delivery'" }
          }
        }
      }
    }
  ]
}

And with attributes on the types (the generation itself still comes from json or fluent):

csharp
[GenerateTypescript(Name = "ApiShipment")]                 // selects the type (in every generation) and names it
public class ShipmentDto
{
    [TypescriptIgnore] public string InternalNote { get; set; } = "";
    [TypescriptProperty(Type = "'Pickup' | 'Consol' | 'Delivery'")] public string Discriminator { get; set; } = "";
    [TypescriptProperty(Name = "no", Optional = true)] public string? Number { get; set; }
}

Output (ShipmentDto with the ABP preset):

ts
// <auto-generated>
//     Generated by Nextended.CodeGen from C# types. Do not edit: changes are lost on the next build.
// </auto-generated>
/* eslint-disable */

import type { AuditedEntityDto } from '../../Volo/Abp/Application/Dtos/AuditedEntityDto';
import type { PortDto } from './PortDto';
import type { ShipmentState } from './ShipmentState';

export interface ApiShipment extends AuditedEntityDto<string> {
    houseBill: string | null;
    state: ShipmentState;
    portOfLoading: PortDto | null;
    countsByState: Partial<Record<keyof typeof ShipmentState, number>>;
    remark?: string | null;
}

Runnable: CodeGenTsSample — three generations of contracts (ts/: ABP preset, enums, namespace folders; ts-const/: Coworkee preset, const objects, flat, aliases; ts-pricing/: own header, optional defaults, a declared union, an options class without its secrets), checked by tsc --strict in TypescriptSampleTests; every rule below has a test in TypescriptGenerationTests.

Settings ​

SettingDefault
OutputPath— (required)the folder; relative to the json file, or the project directory for a fluent generation
DisableGenerationfalse
PropertyNamingCamelCaseCamelCase = JsonNamingPolicy.CamelCase (the ASP.NET Core default), AsIs = no policy
EnumValuesDefaulthow the server writes enums: Number (Default is the same: System.Text.Json without a converter) or String (the member names: a JsonStringEnumConverter registered globally)
EnumStyleEnumEnum: export enum S { A = 0 }. Const: export const S = { A: 0 } as const; + export type S = ... (fits erasableSyntaxOnly)
LongAsString, DecimalAsStringfalselong/ulong/128-bit integers, decimal as string (for servers that write them as strings)
OptionalNullablefalsenullable members also optional: note?: string | null
OptionalDefaultValuesfalsemembers with a default value optional: an initializer other than null/default (= 10, = "", = []), a record parameter default, or [DefaultValue]. Members marked required, [Required] or [JsonRequired] stay required. Meant for request DTOs: set it per type (below) when one generation holds requests and responses
Header—the text at the top of every file (\n line breaks, an empty line follows). Not set: // <auto-generated> ... plus /* eslint-disable */; "": no header
IncludeMembersWithAttributes—only members carrying one of these attributes (full or simple name, Attribute optional), e.g. options classes whose other members are secrets
IncludeTypesWithAttributes—types carrying one of these attributes, in the project and in referenced assemblies; "Name=value" also checks the first constructor argument ("GeneratedCode=Nextended.CodeGen"), see Which types

There are no presets for server setups: describe the serializer with the settings above. Examples: ABP and plain ASP.NET Core (System.Text.Json, camelCase, enums as numbers) need nothing beyond the defaults; a server that registers JsonStringEnumConverter globally needs EnumValues(TypescriptEnumValues.String). Dictionaries with enum keys always use the names (that is what System.Text.Json writes). | TypeAliases | false | Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan as aliases (all string) from scalars.ts | | Layout | Namespace | Namespace: a folder per namespace. Flat: one folder | | RootNamespace | — | the namespace prefix left out of the folders (and of the prefixes that keep same names apart) | | Barrel | true | writes index.ts re-exporting every file | | IncludeNamespaces, IncludeTypes, IncludeBaseTypes | — | which types (below) | | ExcludeNamespaces, ExcludeTypes, ExcludeBaseTypes | — | which not; wins over every include | | IncludeReferencedTypes | true | types the selected ones use (members, bases, union members) are generated too; otherwise unknown and bases flattened | | FromGeneratedDtos | false | also the DTOs this generator generates in the same build | | TypeMap | — | C# type → TypeScript (below) | | Types | — | per type: Name, Ignore, Members with Name, Type, Optional, Ignore; OptionalDefaultValues and IncludeMembersWithAttributes for this type (override the generation's); DerivedTypes and Discriminator (unions without [JsonPolymorphic], below) |

Fluent: Typescript(t => ...) on CodeGenConfig has one method per setting, plus Include<T>()/Include(typeof(...)), Exclude<T>(), IncludeDerivedFrom<T>()/IncludeDerivedFrom(typeof(EntityDto<>)), ExcludeDerivedFrom<T>(), TypeMap<T>(...)/ TypeMap(typeof(...), ...)/TypeMap("Full.Name", ...), and Type<T>(x => ...)/Type("Full.Name", x => ...) with Name(...), Ignore() (the type), Ignore(x => x.A, ...), Property(x => x.A).Name(...).Type(...).Optional().Ignore()/Include(), OptionalDefaultValues(), IncludeMembersWithAttribute<TAttribute>()/IncludeMembersWithAttributes("Name", ...), DerivedType<TDerived>("discriminator")/DerivedType(typeof(...))/DerivedTypes("*") and Discriminator("kind"). The generation has IncludeMembersWithAttribute<TAttribute>() too, and IncludeTypesWithAttribute<TAttribute>(firstArgument)/ IncludeTypesWithAttributes("Name", ...). DtoConfig<T> (and Dto<T>(d => ...)) has Typescript(x => ...) with the same type builder: it applies to every generation, to the DTOs of T (members by their DTO name) and to T itself when a generation selects it.

Which types ​

Real compiled types, so hand-written DTOs, partial classes (all parts) and DTOs written to disk by an earlier build are included:

  • IncludeNamespaces: the namespace and below — also in referenced assemblies (a frontend-types project that references the contracts).

  • IncludeTypes: full or simple names, generic as Page`1 or Page<T>; * matches any text (*Dto, MyApp.Contracts.*).

  • IncludeBaseTypes: every type deriving from or implementing one of them (Volo.Abp.Application.Dtos.EntityDto`1).

  • [GenerateTypescript] on a type selects it in every generation.

  • IncludeTypesWithAttributes: every type carrying one of the attributes (its own attributes; full or simple name, Attribute optional), in the project and in every referenced assembly except the framework's (System*, Microsoft*, Newtonsoft*). "Name=value" also needs the first constructor argument to be that value. Made for a frontend-types project that references the contracts projects, whose generated DTOs carry [GeneratedCode("Nextended.CodeGen", ...)] (see Generated code marker):

    csharp
    Typescript(t => t
        .OutputPath("../frontend/src/types/generated")
        .IncludeTypesWithAttribute<GeneratedCodeAttribute>("Nextended.CodeGen")   // the DTOs of every referenced project
        .ExcludeTypes("*.Internal*"));                                            // Exclude* wins, as always

    Without the argument GeneratedCode also matches the code of other generators (resources classes, API clients); exclude them or name the tool. The DTOs the DTO generator produces in the same run are not in the compilation yet: they come in through FromGeneratedDtos (with it, both select them once). DTOs written to disk by an earlier build are in the compilation and match.

  • FromGeneratedDtos: the DTOs (default DTOs and views) the DTO generator produces in the same run — also those it only adds to the compilation (no OutputPath), with their renames, views, ignores and TypesToIgnore exactly as generated.

  • Out: Exclude*, [TypescriptIgnore], Types[...].Ignore/fluent Ignore(); static classes, attributes, exceptions; interfaces unless chosen by name or attribute; framework types (System.*, Microsoft.*) unless chosen by name.

  • Types the selected ones reference (member types, base types, constraint types, union members) follow with IncludeReferencedTypes.

Following the serializer ​

  • Members: public instance properties with a public getter (and [JsonInclude] members); order of declaration (a partial type: by file, then by position, see Order), [JsonPropertyOrder] first.

  • Names: [JsonPropertyName] (or Newtonsoft [JsonProperty]), else the naming policy; names that are no identifier are quoted ('my-name').

  • [JsonIgnore] (or Condition = Always) leaves the member out; WhenWritingNull/WhenWritingDefault make it optional (?); Never keeps it. [JsonExtensionData] becomes [key: string]: unknown.

  • Enums always carry their values (Draft = 0, Booked = 1, InTransit = 8): numbers, or strings with a string converter — [JsonConverter(typeof(JsonStringEnumConverter))] on the enum (every use) or on a property (that use: keyof typeof State), or EnumValues(String) for the whole generation. String values honour [JsonStringEnumMemberName] and [EnumMember(Value = ...)].

  • [Flags] enums are declared with their numbers; where they are written as strings ("Mail, Push"), the member is string.

  • Dictionaries with enum keys: the serializer writes the names, so Partial<Record<keyof typeof State, number>> (a union of the written names when they differ from the member names).

  • [JsonPolymorphic] + [JsonDerivedType]: the base becomes XBase (common members), every derived type extends XBase with the literal discriminator ($type: 'cat' or the configured TypeDiscriminatorPropertyName, numbers too), and X is the union of the derived types — members typed by the base use the union.

  • Unions without [JsonPolymorphic]: a base type whose derived types the server writes with their own members (OData always does, ABP/System.Text.Json when configured to) is declared in the configuration. DerivedTypes lists the derived types by full or simple name with * globs ("*" = every non-abstract, non-generic derived class of the compilation and of the base's assembly), in the order given; for generated DTOs the entity names match too, so DtoConfig<Place>.Typescript(t => t.DerivedType<AddressPlace>()) works. The base becomes PlaceBase, Place the union, members typed Place use it; a base that is not abstract is a member of its union (VehicleBase | Truck). Discriminators only when the server writes one: "PortPlace=port" (fluent DerivedType<PortPlace>("port")) with Discriminator("kind") (default $type), e.g. Discriminator("@odata.type") with "AddressPlace=#MyApp.AddressPlace" for OData. [JsonDerivedType] on the type wins over the configuration.

    csharp
    Typescript(t => t
        .OutputPath("../frontend/src/types/generated")
        .Type<PlaceDto>(p => p.DerivedTypes("*")));        // json: "Types": { "MyApp.PlaceDto": { "DerivedTypes": [ "*" ] } }
    ts
    export interface PlaceDtoBase extends CustomerOwnedGuidEntityDto {
    }
    export type PlaceDto = AddressPlaceDto | CountryPlaceDto | PortPlaceDto;

Mapping table ​

C#TypeScript
string, char, Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan, Uri, Versionstring (aliases with TypeAliases)
boolboolean
all numeric typesnumber (long/decimal → string by option)
byte[]string (base64)
object, dynamic, JsonElement, JsonNode, JTokenunknown
JsonObject/JObject, JsonArray/JArrayRecord<string, unknown>, unknown[]
every IDictionary<K,V> / IReadOnlyDictionary<K,V>Record<string | number, V>; enum keys as names (above)
KeyValuePair<K,V>{ key: K; value: V } (the naming policy applies)
arrays and every IEnumerable<T> (lists, sets, custom collections)T[]
T?, Nullable<T>T | null
generic types and parametersPage<T extends Entity<string>>, Page<Product>
framework types not listedunknown

TypeMap replaces any type, e.g. ABP's PagedResultDto<T> by your own TypeScript type: the value is the TypeScript name, optionally "Name from 'module'" for an import type (a relative module is relative to OutputPath), type arguments are appended unless the value has its own ("Array<unknown>"). Keys are full names, generic as Ns.Page`1 or Ns.Page<T>; without arity they match every arity.

Nullability, inheritance ​

  • | null from nullable reference types (string?) and Nullable<T>; optional ? only with OptionalNullable, OptionalDefaultValues (members with a default value), [JsonIgnore(Condition = WhenWritingNull)], [TypescriptProperty(Optional = true)] or .Optional() (.Optional(false) keeps one member required).
  • interface Derived extends Base<string> without repeating members; overrides stay with the base, a member hidden with new becomes extends Omit<Base, 'member'>. A base type that is not generated (excluded, or IncludeReferencedTypes = false) is flattened into the derived interface. Abstract types are base interfaces. Circular references are fine (type-only imports).

Files ​

  • One file per type, <Folder>/<Name>.ts; relative import type between files; index.ts re-exports everything.
  • Same names: in different folders they stay, a file that uses both imports one as CrmAddress, the barrel exports both as CrmAddress/SalesAddress; in the flat layout both get the namespace prefix. Types differing only in arity: Page, Page1.
  • Header // <auto-generated> + /* eslint-disable */, or your own text with Header ("" = none). ESLint 9 reports a /* eslint-disable */ that suppresses nothing (reportUnusedDisableDirectives), so a linted folder warns per file with the default header; without it, @typescript-eslint/no-empty-object-type flags interfaces that only extend a base (interface PlaceDtoBase extends EntityDto {}). Simplest: add the folder to the ESLint ignores and set Header without the eslint line. Prettier has no file-level switch: add the folder to .prettierignore.
  • Options classes: IncludeMembersWithAttributes (generation or type) keeps secrets out, e.g. Type<WhiteLabelingOptions>(o => o.IncludeMembersWithAttribute<PublicConfigurationAttribute>()). Property(...).Include() brings a single member back, an empty list on a type turns the generation's filter off for it.
  • Always \n, deterministic order; unchanged files are not rewritten (a checkout with core.autocrlf counts as unchanged).
  • Stale files: the folder holds a manifest (.nextended-typescript) of what was generated; a file no longer generated is deleted (and its empty folder). Files not in the manifest — hand-written ones next to the generated — are never touched. Commit the manifest.

Builds, IDE and CI ​

  • The TypeScript is written when the generator runs: on build, and in the IDE while you type (only changed files). While a source file of a selected type has syntax errors, nothing is written (NCG031), so half-typed code never wipes the output.
  • With the shared compiler server an unchanged project does not run the generator again (the incremental cache): a deleted .ts file comes back with the next change or dotnet build --no-incremental.
  • CI: dotnet build -p:NextendedCodeGenTypescriptCheck=true writes nothing and fails with NCG032 when a generated file differs, is missing or is stale (the property is made visible to the generator by the package's build/Nextended.CodeGen.props). Alternative: build normally and run git diff --exit-code -- path/to/generated.
IdSeverityWhen
NCG030warninga TypeScript generation without OutputPath
NCG031infonot written: a source file of a selected type has syntax errors
NCG032errorcheck mode: the generated TypeScript is not up to date
NCG033warningthe files could not be written (e.g. locked)

Two serializers: ABP and OData ​

One server often answers through two serializers that write the same C# types differently:

ABP / ASP.NET Core MVC (System.Text.Json)OData (Microsoft.AspNetCore.OData)
enumsnumbers ("state": 1), unless a JsonStringEnumConverter is registeredmember names ("state": "Booked", flags "Mail, Push")
member namescamelCase (JsonNamingPolicy.CamelCase)the EDM names: camelCase with EnableLowerCamelCase(), else as declared
derived typesthe declared type only, unless polymorphism is configuredthe members of the runtime type; an instance of a derived type carries "@odata.type": "#Ns.Type"

A generation describes one serializer. For both, use two generations with their own OutputPath (one folder each: the manifest belongs to one generation):

csharp
// REST (ABP): enums as numbers
Typescript(t => t
    .OutputPath("../frontend/src/types/generated")
    .EnumValues(TypescriptEnumValues.Number)    // the default
    .Include<ShipmentDto>());

// OData rows: enums as names, EDM names as declared (no EnableLowerCamelCase), derived types with their @odata.type
Typescript(t => t
    .OutputPath("../frontend/src/types/odata")
    .EnumValues(TypescriptEnumValues.String)
    .PropertyNaming(TypescriptNaming.AsIs)
    .Include<Shipment>()
    .Type<Place>(p => p.DerivedTypes("*")));

The same in codegen.json: two entries of "Typescript" with "EnumValues": "Number" and "EnumValues": "String". Inside one generation a single member can follow the other serializer: [JsonConverter(typeof(JsonStringEnumConverter))] on the property, or .Property(x => x.State).Type("keyof typeof ShipmentState") (names) / .Type("number").

Pilot: ABP frontends with hand-written types ​

For a frontend like CargonerdsApp's frontend/realtime (interfaces, T | null, string for ids and dates, numeric enums with explicit values): the defaults (EnumValues Number, camelCase) give exactly those shapes. Differences to hand-written types to expect: names keep the Dto suffix (rename with Name(...) or re-export under the old names), every member is generated (hand types are often slices with inline objects), nullability follows the C# (string? → | null), and a string discriminator property is string unless it is a [JsonPolymorphic] hierarchy (or .Type("'A' | 'B'")). For OData $select results use Pick<>/Partial<> of the generated types. Further settings from the CargonerdsApp pilot: DerivedTypes("*") for an abstract base the hand types wrote as a union (PlaceDto = AddressPlaceDto | CountryPlaceDto | PortPlaceDto), OptionalDefaultValues() on request DTOs, IncludeMembersWithAttribute<T>() for configuration sent to the client, Header(...) without the eslint line.

Key Features ​

1. DTO Generation from Attributes ​

Automatically generate Data Transfer Objects (DTOs) from your domain classes.

csharp
using Nextended.Core.Attributes;

[AutoGenerateDto(
    ToDtoMethodName = "ToDto",
    ToSourceMethodName = "ToEntity",
    IsComCompatible = true,
    Namespace = "MyApp.Dtos"
)]
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; } // Can be excluded in DTO
}

Generated DTO:

csharp
namespace MyApp.Dtos
{
    public class UserDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

2. Class Generation from JSON/XML ​

Generate strongly-typed classes from configuration files or API responses.

json
// appsettings.json
{
  "Database": {
    "ConnectionString": "Server=localhost;...",
    "MaxPoolSize": 100
  },
  "Api": {
    "BaseUrl": "https://api.example.com",
    "Timeout": 30
  }
}

Configuration:

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Sources/appsettings.json",
      "RootClassName": "ServerConfiguration",
      "Namespace": "MyApp.Configuration"
    }
  ]
}

Generated class:

csharp
namespace MyApp.Configuration
{
    public class ServerConfiguration
    {
        public Database Database { get; set; }
        public Api Api { get; set; }
    }
    
    public class Database
    {
        public string ConnectionString { get; set; }
        public int MaxPoolSize { get; set; }
    }
    
    public class Api
    {
        public string BaseUrl { get; set; }
        public int Timeout { get; set; }
    }
}

3. Excel to Class Generation ​

Generate data classes and static lookup tables from Excel spreadsheets.

json
{
  "ExcelGenerations": [
    {
      "ModelType": "RecordStruct",
      "SourceFile": "/Sources/countries.xlsx",
      "Namespace": "MyApp.Data",
      "RootClassName": "Country",
      "KeyColumn": "A",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "GenerateModelClass": true,
      "GenerateStaticTable": true,
      "StaticClassName": "Countries",
      "GenerateAllCollection": true
    }
  ]
}

Configuration ​

Project Setup ​

  1. Add packages to your .csproj:
xml
<ItemGroup>
  <PackageReference Include="Nextended.CodeGen" Version="10.1.22" />
  <PackageReference Include="Nextended.Core" Version="10.1.22" PrivateAssets="all" GeneratePathProperty="true" />
</ItemGroup>
  1. Create CodeGen.config.json:
json
{
  "DtoGeneration": {
    "ComIdClassName": "ComGuids",
    "ComIdClassPropertyFormat": "Id{0}",
    "ComIdClassModifier": "Public",
    "OneFilePerClass": true,
    "CreateRegions": true,
    "CreateComments": true,
    "GeneratePartial": true,
    "Namespace": "MyApp.Generated",
    "Suffix": "Dto"
  },
  "StructureGenerations": [
    {
      "SourceFile": "/Sources/appsettings.json",
      "RootClassName": "AppSettings",
      "Namespace": "MyApp.Configuration"
    }
  ]
}
  1. Add config file to .csproj:
xml
<ItemGroup>
  <AdditionalFiles Include="CodeGen.config.json" />
</ItemGroup>

Usage Examples ​

Basic DTO Generation ​

csharp
using Nextended.Core.Attributes;

[AutoGenerateDto]
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public DateTime CreatedDate { get; set; }
}

// Usage after build
var product = new Product 
{ 
    Id = 1, 
    Name = "Widget", 
    Price = 99.99m 
};

var dto = product.ToDto(); // Generated extension method
var backToEntity = dto.ToEntity(); // Round-trip conversion

Advanced DTO Configuration ​

csharp
[AutoGenerateDto(
    Suffix = "Dto",
    Prefix = null,
    ToDtoMethodName = "ToTransferObject",
    ToSourceMethodName = "ToModel",
    Namespace = "MyApp.Dtos",
    IsComCompatible = true,
    GeneratePartial = true
)]
public class Order
{
    public int Id { get; set; }
    public string OrderNumber { get; set; }
    public List<OrderItem> Items { get; set; }
    public Customer Customer { get; set; }
    
    [IgnoreInDto]
    public string InternalNotes { get; set; }
}

Configuration from JSON ​

appsettings.json:

json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=MyDb;..."
  },
  "Features": {
    "EnableCache": true,
    "MaxRetries": 3
  }
}

CodeGen.config.json:

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Sources/appsettings.json",
      "RootClassName": "AppConfiguration",
      "Namespace": "MyApp.Config",
      "Ignore": ["Logging.LogLevel.Microsoft"]
    }
  ]
}

Usage:

csharp
var config = new AppConfiguration();
var connectionString = config.ConnectionStrings.DefaultConnection;

Excel Data Generation ​

Excel file structure:

CodeNameCountryActive
USUnited StatesUSAYes
UKUnited KingdomGBRYes
CACanadaCANYes

Configuration:

json
{
  "ExcelGenerations": [
    {
      "SourceFile": "/Sources/locations.xlsx",
      "Namespace": "MyApp.Data",
      "RootClassName": "Location",
      "KeyColumn": "A",
      "StaticClassName": "Locations",
      "GenerateStaticTable": true,
      "ColumnMappings": {
        "Code": "LocationCode",
        "Name": "LocationName"
      }
    }
  ]
}

Generated code:

csharp
public record struct Location
{
    public string LocationCode { get; init; }
    public string LocationName { get; init; }
    public string Country { get; init; }
    public string Active { get; init; }
}

public static class Locations
{
    public static Location US => new() 
    { 
        LocationCode = "US", 
        LocationName = "United States",
        Country = "USA",
        Active = "Yes"
    };
    
    public static Location UK => new() 
    { 
        LocationCode = "UK", 
        LocationName = "United Kingdom",
        Country = "GBR",
        Active = "Yes"
    };
    
    public static IReadOnlyList<Location> All { get; } = new[]
    {
        US, UK, CA
    };
}

Usage:

csharp
var usLocation = Locations.US;
var allLocations = Locations.All;

Detailed Generation Examples ​

JSON Structure Generation ​

Generate strongly-typed classes from JSON files such as configuration files, API responses, or data schemas.

Example 1: Application Configuration ​

Source File: appsettings.json

json
{
  "Database": {
    "ConnectionString": "Server=localhost;Database=MyApp;",
    "Timeout": 30,
    "MaxRetryCount": 3
  },
  "Redis": {
    "Host": "localhost",
    "Port": 6379,
    "DefaultDatabase": 0
  },
  "Security": {
    "JwtSecret": "your-secret-key",
    "TokenExpirationMinutes": 60,
    "EnableTwoFactor": true
  },
  "Features": {
    "EnableCache": true,
    "EnableLogging": true,
    "MaxUploadSizeMB": 10
  }
}

Configuration: CodeGen.config.json

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Sources/appsettings.json",
      "RootClassName": "ApplicationSettings",
      "Namespace": "MyApp.Configuration",
      "Prefix": "App",
      "OutputPath": "./Generated/Configuration/"
    }
  ]
}

Generated Classes:

csharp
namespace MyApp.Configuration
{
    public class AppApplicationSettings
    {
        public Database Database { get; set; }
        public Redis Redis { get; set; }
        public Security Security { get; set; }
        public Features Features { get; set; }
    }

    public class Database
    {
        public string ConnectionString { get; set; }
        public int Timeout { get; set; }
        public int MaxRetryCount { get; set; }
    }

    public class Redis
    {
        public string Host { get; set; }
        public int Port { get; set; }
        public int DefaultDatabase { get; set; }
    }

    public class Security
    {
        public string JwtSecret { get; set; }
        public int TokenExpirationMinutes { get; set; }
        public bool EnableTwoFactor { get; set; }
    }

    public class Features
    {
        public bool EnableCache { get; set; }
        public bool EnableLogging { get; set; }
        public int MaxUploadSizeMB { get; set; }
    }
}

Usage:

csharp
using MyApp.Configuration;

// Use the generated strongly-typed configuration
var settings = new AppApplicationSettings
{
    Database = new Database 
    { 
        ConnectionString = "...",
        Timeout = 30 
    }
};

// Access with IntelliSense support
var timeout = settings.Database.Timeout;
var enableCache = settings.Features.EnableCache;

Example 2: API Response Schema ​

Source File: user-api-response.json

json
{
  "user": {
    "id": 123,
    "username": "john_doe",
    "email": "john@example.com",
    "profile": {
      "firstName": "John",
      "lastName": "Doe",
      "avatar": "https://example.com/avatar.jpg",
      "bio": "Software Developer"
    },
    "settings": {
      "notifications": {
        "email": true,
        "push": false,
        "sms": true
      },
      "privacy": {
        "profileVisible": true,
        "showEmail": false
      }
    },
    "metadata": {
      "createdAt": "2024-01-01T00:00:00Z",
      "lastLogin": "2024-06-15T10:30:00Z",
      "accountStatus": "active"
    }
  }
}

Configuration:

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Sources/user-api-response.json",
      "RootClassName": "UserApiResponse",
      "Namespace": "MyApp.ApiModels",
      "Ignore": ["metadata.lastLogin"]
    }
  ]
}

Generated Classes:

csharp
namespace MyApp.ApiModels
{
    public class UserApiResponse
    {
        public User User { get; set; }
    }

    public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public Profile Profile { get; set; }
        public Settings Settings { get; set; }
        public Metadata Metadata { get; set; }
    }

    public class Profile
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Avatar { get; set; }
        public string Bio { get; set; }
    }

    public class Settings
    {
        public Notifications Notifications { get; set; }
        public Privacy Privacy { get; set; }
    }

    public class Notifications
    {
        public bool Email { get; set; }
        public bool Push { get; set; }
        public bool Sms { get; set; }
    }

    public class Privacy
    {
        public bool ProfileVisible { get; set; }
        public bool ShowEmail { get; set; }
    }

    public class Metadata
    {
        public string CreatedAt { get; set; }
        public string AccountStatus { get; set; }
    }
}

XML Structure Generation ​

Generate classes from XML files using the same configuration structure.

Source File: config.xml

xml
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
  <Server>
    <Host>localhost</Host>
    <Port>8080</Port>
    <EnableSSL>true</EnableSSL>
  </Server>
  <Logging>
    <Level>Information</Level>
    <FilePath>./logs/app.log</FilePath>
    <MaxFileSizeMB>50</MaxFileSizeMB>
  </Logging>
</Configuration>

Configuration:

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Sources/config.xml",
      "RootClassName": "ServerConfiguration",
      "Namespace": "MyApp.XmlConfig"
    }
  ]
}

Generated Classes:

csharp
namespace MyApp.XmlConfig
{
    public class ServerConfiguration
    {
        public Server Server { get; set; }
        public Logging Logging { get; set; }
    }

    public class Server
    {
        public string Host { get; set; }
        public int Port { get; set; }
        public bool EnableSSL { get; set; }
    }

    public class Logging
    {
        public string Level { get; set; }
        public string FilePath { get; set; }
        public int MaxFileSizeMB { get; set; }
    }
}

Excel Generation (Advanced) ​

Generate data models and static lookup tables from Excel spreadsheets. This is particularly useful for reference data, lookup tables, and configuration data.

Example 1: Country/Region Codes ​

Excel File Structure: countries.xlsx

CodeNameISO3NumericCodePhonePrefixCapital
USUnited StatesUSA840+1Washington, D.C.
GBUnited KingdomGBR826+44London
DEGermanyDEU276+49Berlin
JPJapanJPN392+81Tokyo
CACanadaCAN124+1Ottawa

Configuration:

json
{
  "ExcelGenerations": [
    {
      "ModelType": "RecordStruct",
      "SourceFile": "/Sources/countries.xlsx",
      "SheetName": null,
      "Namespace": "MyApp.Data.Geography",
      "RootClassName": "Country",
      "KeyColumn": "A",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "GenerateModelClass": true,
      "GenerateStaticTable": true,
      "StaticClassName": "Countries",
      "GenerateAllCollection": true,
      "ColumnMappings": {
        "Code": "IsoCode",
        "ISO3": "Iso3Code"
      },
      "PropertyTypeOverrides": {
        "NumericCode": "int",
        "PhonePrefix": "string"
      }
    }
  ]
}

Generated Code:

csharp
namespace MyApp.Data.Geography
{
    // Model class
    public record struct Country
    {
        public string IsoCode { get; init; }
        public string Name { get; init; }
        public string Iso3Code { get; init; }
        public int NumericCode { get; init; }
        public string PhonePrefix { get; init; }
        public string Capital { get; init; }
    }

    // Static lookup table
    public static class Countries
    {
        public static Country US => new Country
        {
            IsoCode = "US",
            Name = "United States",
            Iso3Code = "USA",
            NumericCode = 840,
            PhonePrefix = "+1",
            Capital = "Washington, D.C."
        };

        public static Country GB => new Country
        {
            IsoCode = "GB",
            Name = "United Kingdom",
            Iso3Code = "GBR",
            NumericCode = 826,
            PhonePrefix = "+44",
            Capital = "London"
        };

        public static Country DE => new Country
        {
            IsoCode = "DE",
            Name = "Germany",
            Iso3Code = "DEU",
            NumericCode = 276,
            PhonePrefix = "+49",
            Capital = "Berlin"
        };

        // ... more countries

        public static IReadOnlyList<Country> All { get; } = new[]
        {
            US, GB, DE, JP, CA
        };

        public static Country GetByCode(string code)
        {
            return All.FirstOrDefault(c => c.IsoCode == code);
        }
    }
}

Usage:

csharp
using MyApp.Data.Geography;

// Access individual countries
var usa = Countries.US;
Console.WriteLine($"{usa.Name} - {usa.PhonePrefix}");

// Get all countries
var allCountries = Countries.All;
foreach (var country in allCountries)
{
    Console.WriteLine($"{country.Name} ({country.IsoCode})");
}

// Lookup by code
var germany = Countries.GetByCode("DE");

Example 2: Product Categories with Hierarchies ​

Excel File: product-categories.xlsx

CategoryIdCategoryNameParentIdSortOrderActiveDescription
1Electronics1YElectronic devices and accessories
2Computers11YDesktop and laptop computers
3Laptops21YPortable computers
4Desktops22YDesktop computers
5Smartphones12YMobile phones

Configuration:

json
{
  "ExcelGenerations": [
    {
      "ModelType": "Class",
      "SourceFile": "/Sources/product-categories.xlsx",
      "Namespace": "MyApp.Catalog",
      "RootClassName": "ProductCategory",
      "KeyColumn": "A",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "GenerateModelClass": true,
      "GenerateStaticTable": true,
      "StaticClassName": "ProductCategories",
      "GenerateAllCollection": true,
      "PropertyTypeOverrides": {
        "CategoryId": "int",
        "ParentId": "int?",
        "SortOrder": "int",
        "Active": "bool"
      },
      "ColumnMappings": {
        "Active": "IsActive"
      }
    }
  ]
}

Generated Classes:

csharp
namespace MyApp.Catalog
{
    public class ProductCategory
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public int? ParentId { get; set; }
        public int SortOrder { get; set; }
        public bool IsActive { get; set; }
        public string Description { get; set; }
    }

    public static class ProductCategories
    {
        public static ProductCategory Electronics => new ProductCategory
        {
            CategoryId = 1,
            CategoryName = "Electronics",
            ParentId = null,
            SortOrder = 1,
            IsActive = true,
            Description = "Electronic devices and accessories"
        };

        public static ProductCategory Computers => new ProductCategory
        {
            CategoryId = 2,
            CategoryName = "Computers",
            ParentId = 1,
            SortOrder = 1,
            IsActive = true,
            Description = "Desktop and laptop computers"
        };

        // ... more categories

        public static IReadOnlyList<ProductCategory> All { get; } = new[]
        {
            Electronics,
            Computers,
            Laptops,
            Desktops,
            Smartphones
        };

        public static ProductCategory GetById(int id)
        {
            return All.FirstOrDefault(c => c.CategoryId == id);
        }

        public static IEnumerable<ProductCategory> GetChildren(int parentId)
        {
            return All.Where(c => c.ParentId == parentId);
        }
    }
}

Usage:

csharp
using MyApp.Catalog;

// Get root categories
var rootCategories = ProductCategories.All
    .Where(c => c.ParentId == null);

// Get children of Electronics
var electronicsChildren = ProductCategories.GetChildren(1);

// Build category tree
var category = ProductCategories.Computers;
Console.WriteLine($"{category.CategoryName}: {category.Description}");

Excel Generation Configuration Options ​

PropertyTypeDescription
ModelTypestringType of model to generate: Class, Struct, Record, RecordStruct
SourceFilestringPath to the Excel file (relative to project root)
SheetNamestring?Specific sheet name. If null, uses first sheet
NamespacestringNamespace for generated classes
RootClassNamestringName of the model class
KeyColumnstringColumn letter to use as key (e.g., "A", "B")
HeaderRowIndexintRow number containing column headers (1-based)
DataStartRowIndexintFirst row containing data (1-based)
GenerateModelClassboolWhether to generate the model class
GenerateStaticTableboolWhether to generate static lookup class
StaticClassNamestringName of the static lookup class
GenerateAllCollectionboolWhether to generate All property with all records
ColumnMappingsobjectDictionary mapping Excel column names to property names
PropertyTypeOverridesobjectDictionary specifying custom types for properties
OutputPathstring?Custom output path for generated files

Tips for Excel Generation ​

  1. Column Headers: Use clear, descriptive names in the header row. These become property names.

  2. Data Types: By default, all columns are strings. Use PropertyTypeOverrides to specify correct types:

    json
    "PropertyTypeOverrides": {
      "Id": "int",
      "Price": "decimal",
      "IsActive": "bool",
      "CreatedDate": "DateTime"
    }
  3. Naming: Use ColumnMappings to rename columns that don't follow C# naming conventions:

    json
    "ColumnMappings": {
      "Full Name": "FullName",
      "E-Mail": "Email",
      "ZIP Code": "PostalCode"
    }
  4. Model Types:

    • RecordStruct: Immutable, value type, best for small lookup data
    • Record: Immutable, reference type, good for DTOs
    • Class: Mutable, reference type, most flexible
    • Struct: Mutable, value type, for small data structures
  5. Key Column: Choose a unique identifier column (usually first column) for generating property accessors.

AutoGenerateDto Attribute Reference ​

The AutoGenerateDto attribute is applied to classes or enums to generate DTOs at compile-time.

Basic Usage ​

csharp
[AutoGenerateDto]
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}
// Generates: UserDto class with mapping methods

Attribute Properties ​

Namespace and Naming ​

PropertyTypeDefaultDescription
NamespacestringnullTarget namespace for generated DTO. If null, uses source class namespace
Prefixstring""Prefix for generated class name (e.g., "Com" → "ComUserDto")
Suffixstring"Dto"Suffix for generated class name (e.g., "Dto" → "UserDto")
GeneratedClassNamestringnullOverride complete class name. Ignores prefix/suffix if set

Example:

csharp
[AutoGenerateDto(
    Namespace = "MyApp.Api.Dtos",
    Prefix = "Api",
    Suffix = "Response"
)]
public class User { }
// Generates: MyApp.Api.Dtos.ApiUserResponse

Mapping Configuration ​

PropertyTypeDefaultDescription
GenerateMappingbooltrueGenerate extension methods for mapping (ToDto/ToSource)
ToDtoMethodNamestringnullName of the method to convert source to DTO (e.g., "ToDto")
ToSourceMethodNamestringnullName of the method to convert DTO back to source (e.g., "ToEntity")
MappingStrategyDtoMappingStrategyDefaultExtensions (generated extension methods) or Mapperly (generated partial Mapperly mapper, see Mapperly instead of extension methods); Default follows DefaultMappingSettings.Strategy

Example:

csharp
[AutoGenerateDto(
    ToDtoMethodName = "ToApiModel",
    ToSourceMethodName = "ToEntity"
)]
public class User { }

// Usage:
var dto = user.ToApiModel();
var entity = dto.ToEntity();

Property Control ​

PropertyTypeDefaultDescription
PropertiesToIgnorestring[]nullProperty names to exclude from DTO generation

Example:

csharp
[AutoGenerateDto(PropertiesToIgnore = new[] { "Password", "InternalId" })]
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }  // Not included in DTO
    public Guid InternalId { get; set; }  // Not included in DTO
}

Alternative: Use [IgnoreOnGeneration] attribute on properties:

csharp
public class User
{
    public int Id { get; set; }
    
    [IgnoreOnGeneration]
    public string Password { get; set; }  // Not included in DTO
}

Inheritance and Interfaces ​

PropertyTypeDefaultDescription
BaseTypestringnullBase type for generated DTO (e.g., "BaseDto")
Interfacesstring[]nullInterfaces to implement (e.g., "IDto", "IValidatable")
AutoGenerateDerivedboolfalseAutomatically generate DTOs for derived classes

Example:

csharp
[AutoGenerateDto(
    BaseType = "EntityBase",
    Interfaces = new[] { "IDto", "IAuditable" }
)]
public class User { }

// Generates:
public class UserDto : EntityBase, IDto, IAuditable
{
    // Properties...
}

COM Compatibility ​

PropertyTypeDefaultDescription
IsComCompatibleboolfalseGenerate COM-visible and COM-compatible code with GUIDs

Example:

csharp
[AutoGenerateDto(IsComCompatible = true)]
public class User { }

// Generates:
[ComVisible(true)]
[Guid("...")]
public class UserDto
{
    // Properties...
}

Modifiers and Access ​

PropertyTypeDefaultDescription
ClassModifierModifierPublicAccess modifier for generated class (Public, Internal, Private)
InterfaceModifierModifierPublicAccess modifier for generated interface
DefaultPropertyInterfaceAccessInterfacePropertyGetSetDefault property access in interface (Get, Set, GetSet)

Example:

csharp
[AutoGenerateDto(
    ClassModifier = Modifier.Internal,
    InterfaceModifier = Modifier.Public
)]
public class User { }

Attributes and Metadata ​

PropertyTypeDefaultDescription
KeepAttributesOnGeneratedClassboolfalseCopy attributes from source class to DTO
KeepAttributesOnGeneratedInterfaceboolfalseCopy attributes from source class to generated interface
KeepPropertyAttributesOnGeneratedClassboolfalseCopy property attributes to DTO properties
KeepPropertyAttributesOnGeneratedInterfaceboolfalseCopy property attributes to interface properties
PreClassStringstringnullString to add before class (e.g., attributes)
PreInterfaceStringstringnullString to add before interface (e.g., attributes)

The property settings reach every member of the generated class: scalar members (string, decimal, ...), enum members and collections get the attributes on the property itself. A member whose type is another generated DTO class keeps them on its explicit interface implementation, where they have always been written. On an enum, KeepAttributesOnGeneratedClass and the enum's own PreClassString apply as well (see Enums).

Example:

csharp
[AutoGenerateDto(
    PreClassString = "[Serializable]\n[JsonObject]",
    KeepPropertyAttributesOnGeneratedClass = true
)]
public class User
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
}

// Generates:
[Serializable]
[JsonObject]
public class UserDto
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
}

Namespaces and Using Directives ​

PropertyTypeDefaultDescription
Usingsstring[]nullAdditional using directives
AddReferencedNamespacesUsingsboolfalseAdd usings for all referenced namespaces
AddContainingNamespaceUsingsboolfalseAdd using for source class namespace

Example:

csharp
[AutoGenerateDto(
    Usings = new[] { "System.ComponentModel.DataAnnotations", "MyApp.Helpers" },
    AddReferencedNamespacesUsings = true
)]
public class User { }

Complete Example ​

csharp
using Nextended.Core.Attributes;
using Nextended.Core.Enums;

[AutoGenerateDto(
    // Naming
    Namespace = "MyApp.Api.Dtos",
    Suffix = "Response",
    
    // Mapping
    ToDtoMethodName = "ToApiResponse",
    ToSourceMethodName = "ToEntity",
    
    // Inheritance
    BaseType = "BaseResponse",
    Interfaces = new[] { "IApiResponse" },
    
    // Properties
    PropertiesToIgnore = new[] { "PasswordHash", "InternalData" },
    
    // Modifiers
    ClassModifier = Modifier.Public,
    
    // Attributes
    KeepPropertyAttributesOnGeneratedClass = true,
    PreClassString = "[Serializable]",
    
    // Namespaces
    Usings = new[] { "System.ComponentModel.DataAnnotations" }
)]
public class User
{
    public int Id { get; set; }
    
    [Required]
    [StringLength(100)]
    public string Username { get; set; }
    
    [EmailAddress]
    public string Email { get; set; }
    
    [IgnoreOnGeneration]
    public string PasswordHash { get; set; }
    
    public DateTime CreatedAt { get; set; }
}

// Usage:
var user = GetUser();
var response = user.ToApiResponse();
var userAgain = response.ToEntity();

Configuration Options ​

DtoGeneration Options (CodeGen.config.json) ​

These settings apply to all DTOs unless overridden by attribute properties.

OptionTypeDescription
NamespacestringDefault namespace for generated DTOs
SuffixstringDefault suffix for DTO class names (default: "Dto")
PrefixstringDefault prefix for DTO class names
ToDtoMethodNamestringDefault name of ToDto extension method
ToSourceMethodNamestringDefault name of ToSource extension method
IsComCompatibleboolGenerate COM-compatible GUIDs by default
GeneratePartialboolGenerate as partial classes (default: true)
OneFilePerClassboolCreate separate file per DTO (default: true)
CreateRegionsboolAdd region blocks (default: true)
CreateCommentsboolAdd XML comments (default: true)
ComIdClassNamestringName of the class for COM GUIDs
ComIdClassPropertyFormatstringFormat for COM ID properties
ComIdClassModifierstringModifier for COM ID class
BaseTypestringDefault base type for DTOs
Interfacesstring[]Default interfaces for DTOs
Usingsstring[]Default using directives
KeepAttributesOnGeneratedClassboolCopy attributes from source classes
KeepAttributesOnGeneratedInterfaceboolCopy attributes to interfaces
AddReferencedNamespacesUsingsboolAdd usings for referenced namespaces
AddContainingNamespaceUsingsboolAdd using for source namespaces
PreInterfaceStringstringString before generated interfaces
PreClassStringstringString before generated classes
DefaultMappingSettingsobjectDefault mapping settings configuration
OutputPathstringOutput directory for generated files
PropertiesToIgnorestring[]Property names left out of every DTO whose attribute has no own list
TypesToIgnorestring[]Types that get no DTO, see Leaving types out
KeepEnumFlagsAndUnderlyingTypeboolGenerated enums keep [Flags] and the underlying type (default: false), see Enums
InitializeCollectionsboolCollection properties start as [] (default: false), see Collections start empty
DeleteStaleFilesboolDeletes generated files that the generation no longer writes (default: false), see Where the files land
GeneratedCodeAttributebool[GeneratedCode("Nextended.CodeGen", null)] on every generated type (default: true), see Generated code marker
GeneratedCodeVersionboolThe generator's package version in that attribute instead of null (default: false)

StructureGeneration Options (JSON/XML) ​

Complete reference for generating classes from JSON and XML files.

OptionTypeRequiredDescription
SourceFilestringYesPath to JSON or XML source file (relative to project root)
RootClassNamestringYesName of the root generated class
NamespacestringYesTarget namespace for generated classes
PrefixstringNoPrefix for all generated class names
SuffixstringNoSuffix for all generated class names
Ignorestring[]NoProperty paths to ignore (e.g., "Database.Password")
OutputPathstringNoOutput directory for generated files (if null, added to compilation)
GeneratedCodeAttributeboolNo[GeneratedCode] on the generated classes (default: true)
GeneratedCodeVersionboolNoThe generator's package version in it (default: false)

JSON Generation Examples ​

Basic Configuration File:

appsettings.json:

json
{
  "Database": {
    "ConnectionString": "Server=localhost;Database=MyDb;",
    "MaxPoolSize": 100,
    "EnableLogging": true
  },
  "Api": {
    "BaseUrl": "https://api.example.com",
    "Timeout": 30,
    "ApiKey": "secret-key"
  }
}

Configuration:

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Config/appsettings.json",
      "RootClassName": "AppSettings",
      "Namespace": "MyApp.Configuration"
    }
  ]
}

Generated Code:

csharp
namespace MyApp.Configuration
{
    public class AppSettings
    {
        public Database Database { get; set; }
        public Api Api { get; set; }
    }

    public class Database
    {
        public string ConnectionString { get; set; }
        public int MaxPoolSize { get; set; }
        public bool EnableLogging { get; set; }
    }

    public class Api
    {
        public string BaseUrl { get; set; }
        public int Timeout { get; set; }
        public string ApiKey { get; set; }
    }
}

Usage:

csharp
var config = new AppSettings
{
    Database = new Database
    {
        ConnectionString = "...",
        MaxPoolSize = 100
    }
};

Advanced with Ignore:

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Config/appsettings.json",
      "RootClassName": "AppSettings",
      "Namespace": "MyApp.Configuration",
      "Prefix": "Cfg",
      "Ignore": ["Api.ApiKey", "Database.ConnectionString"],
      "OutputPath": "./Generated/Config/"
    }
  ]
}

Complex JSON Structure:

users.json:

json
{
  "users": [
    {
      "id": 1,
      "name": "John Doe",
      "email": "john@example.com",
      "roles": ["admin", "user"],
      "metadata": {
        "lastLogin": "2024-01-15T10:30:00Z",
        "loginCount": 42
      }
    }
  ],
  "pagination": {
    "page": 1,
    "pageSize": 10,
    "total": 100
  }
}

Generated Classes:

csharp
public class UsersRoot
{
    public List<User> Users { get; set; }
    public Pagination Pagination { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public List<string> Roles { get; set; }
    public Metadata Metadata { get; set; }
}

public class Metadata
{
    public DateTime LastLogin { get; set; }
    public int LoginCount { get; set; }
}

public class Pagination
{
    public int Page { get; set; }
    public int PageSize { get; set; }
    public int Total { get; set; }
}

XML Generation Examples ​

Simple XML Configuration:

xml
<!-- config.xml -->
<Configuration>
  <Server>
    <Host>localhost</Host>
    <Port>8080</Port>
    <UseSSL>true</UseSSL>
  </Server>
  <Logging>
    <Level>Information</Level>
    <FilePath>logs/app.log</FilePath>
  </Logging>
</Configuration>

Configuration:

json
{
  "StructureGenerations": [
    {
      "SourceFile": "/Config/config.xml",
      "RootClassName": "Configuration",
      "Namespace": "MyApp.Config"
    }
  ]
}

Generated Code:

csharp
namespace MyApp.Config
{
    public class Configuration
    {
        public Server Server { get; set; }
        public Logging Logging { get; set; }
    }

    public class Server
    {
        public string Host { get; set; }
        public int Port { get; set; }
        public bool UseSSL { get; set; }
    }

    public class Logging
    {
        public string Level { get; set; }
        public string FilePath { get; set; }
    }
}

ExcelGeneration Options ​

Complete reference for generating classes from Excel spreadsheets.

OptionTypeRequiredDescription
SourceFilestringYesPath to Excel file (.xlsx, .xls)
SheetNamestringNoSpecific sheet name (null for first sheet)
NamespacestringYesTarget namespace for generated classes
RootClassNamestringYesName of the model/record class
StaticClassNamestringNoName of the static lookup class
KeyColumnstringNoColumn letter to use as key (e.g., "A", "B")
HeaderRowIndexintYesRow number containing column headers (1-based)
DataStartRowIndexintYesFirst row number containing data (1-based)
ModelTypestringNoType of model: "Class", "RecordClass", "RecordStruct" (default: "Class")
GenerateModelClassboolNoGenerate the model/record class (default: true)
GenerateStaticTableboolNoGenerate static lookup class with data (default: false)
GeneratedCodeAttributeboolNo[GeneratedCode] on the model and table classes (default: true)
GeneratedCodeVersionboolNoThe generator's package version in it (default: false)
GenerateAllCollectionboolNoGenerate collection of all records (default: false)
ColumnMappingsDictionary<string,string>NoMap Excel column names to property names
PropertyTypeOverridesDictionary<string,string>NoOverride property types
OutputPathstringNoOutput directory for generated files

Excel Generation Examples ​

Example 1: Simple Data Table

Excel File (countries.xlsx):

| Code | Name           | Population | Capital    |
|------|----------------|------------|------------|
| US   | United States  | 331000000  | Washington |
| UK   | United Kingdom | 67000000   | London     |
| FR   | France         | 65000000   | Paris      |

Configuration:

json
{
  "ExcelGenerations": [
    {
      "SourceFile": "/Data/countries.xlsx",
      "Namespace": "MyApp.Data",
      "RootClassName": "Country",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "GenerateModelClass": true
    }
  ]
}

Generated Code:

csharp
namespace MyApp.Data
{
    public class Country
    {
        public string Code { get; set; }
        public string Name { get; set; }
        public int Population { get; set; }
        public string Capital { get; set; }
    }
}

Example 2: Static Lookup Table

Configuration:

json
{
  "ExcelGenerations": [
    {
      "SourceFile": "/Data/countries.xlsx",
      "Namespace": "MyApp.Data",
      "RootClassName": "Country",
      "StaticClassName": "Countries",
      "KeyColumn": "A",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "GenerateModelClass": true,
      "GenerateStaticTable": true,
      "GenerateAllCollection": true
    }
  ]
}

Generated Code:

csharp
namespace MyApp.Data
{
    public class Country
    {
        public string Code { get; set; }
        public string Name { get; set; }
        public int Population { get; set; }
        public string Capital { get; set; }
    }

    public static class Countries
    {
        public static Country US { get; } = new Country
        {
            Code = "US",
            Name = "United States",
            Population = 331000000,
            Capital = "Washington"
        };

        public static Country UK { get; } = new Country
        {
            Code = "UK",
            Name = "United Kingdom",
            Population = 67000000,
            Capital = "London"
        };

        public static Country FR { get; } = new Country
        {
            Code = "FR",
            Name = "France",
            Population = 65000000,
            Capital = "Paris"
        };

        public static IReadOnlyList<Country> All { get; } = new[]
        {
            US, UK, FR
        };
    }
}

Usage:

csharp
// Access by key
var us = Countries.US;
Console.WriteLine($"{us.Name}: {us.Population}");

// Access all
foreach (var country in Countries.All)
{
    Console.WriteLine(country.Name);
}

// Find by code
var france = Countries.All.FirstOrDefault(c => c.Code == "FR");

Example 3: Record Struct with Column Mapping

Excel File (products.xlsx):

| Product ID | Product Name    | Unit Price | In Stock |
|------------|-----------------|------------|----------|
| P001       | Widget A        | 19.99      | Yes      |
| P002       | Gadget B        | 29.99      | No       |

Configuration:

json
{
  "ExcelGenerations": [
    {
      "SourceFile": "/Data/products.xlsx",
      "Namespace": "MyApp.Catalog",
      "RootClassName": "Product",
      "ModelType": "RecordStruct",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "ColumnMappings": {
        "Product ID": "ProductId",
        "Product Name": "Name",
        "Unit Price": "Price",
        "In Stock": "Available"
      }
    }
  ]
}

Generated Code:

csharp
namespace MyApp.Catalog
{
    public record struct Product
    {
        public string ProductId { get; init; }
        public string Name { get; init; }
        public double Price { get; init; }
        public string Available { get; init; }
    }
}

Example 4: Custom Property Types

Excel File (locations.xlsx):

| Code | Name        | Coordinates      | Status  | Type      |
|------|-------------|------------------|---------|-----------|
| NYC  | New York    | 40.7128,-74.0060 | Active  | Primary   |
| LAX  | Los Angeles | 34.0522,-118.2437| Active  | Secondary |

Custom Types:

csharp
namespace MyApp.Types
{
    public record struct Coordinates
    {
        public double Latitude { get; init; }
        public double Longitude { get; init; }

        public static Coordinates Parse(string value)
        {
            var parts = value.Split(',');
            return new Coordinates
            {
                Latitude = double.Parse(parts[0]),
                Longitude = double.Parse(parts[1])
            };
        }
    }

    public enum LocationStatus { Active, Inactive }
    public enum LocationType { Primary, Secondary, Tertiary }
}

Configuration:

json
{
  "ExcelGenerations": [
    {
      "SourceFile": "/Data/locations.xlsx",
      "Namespace": "MyApp.Data",
      "RootClassName": "Location",
      "StaticClassName": "Locations",
      "KeyColumn": "A",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "ModelType": "RecordStruct",
      "GenerateStaticTable": true,
      "PropertyTypeOverrides": {
        "Coordinates": "MyApp.Types.Coordinates",
        "Status": "MyApp.Types.LocationStatus",
        "Type": "MyApp.Types.LocationType"
      },
      "ColumnMappings": {
        "Status": "Status",
        "Type": "Type"
      }
    }
  ]
}

Generated Code:

csharp
namespace MyApp.Data
{
    public record struct Location
    {
        public string Code { get; init; }
        public string Name { get; init; }
        public MyApp.Types.Coordinates Coordinates { get; init; }
        public MyApp.Types.LocationStatus Status { get; init; }
        public MyApp.Types.LocationType Type { get; init; }
    }

    public static class Locations
    {
        public static Location NYC { get; } = new Location
        {
            Code = "NYC",
            Name = "New York",
            Coordinates = MyApp.Types.Coordinates.Parse("40.7128,-74.0060"),
            Status = MyApp.Types.LocationStatus.Active,
            Type = MyApp.Types.LocationType.Primary
        };

        public static Location LAX { get; } = new Location
        {
            Code = "LAX",
            Name = "Los Angeles",
            Coordinates = MyApp.Types.Coordinates.Parse("34.0522,-118.2437"),
            Status = MyApp.Types.LocationStatus.Active,
            Type = MyApp.Types.LocationType.Secondary
        };
    }
}

Example 5: Multiple Sheets

json
{
  "ExcelGenerations": [
    {
      "SourceFile": "/Data/masterdata.xlsx",
      "SheetName": "Customers",
      "Namespace": "MyApp.Data",
      "RootClassName": "Customer",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2
    },
    {
      "SourceFile": "/Data/masterdata.xlsx",
      "SheetName": "Products",
      "Namespace": "MyApp.Data",
      "RootClassName": "Product",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2
    }
  ]
}

Example 6: Complete Real-World Scenario

Excel File (scac_codes.xlsx) - Shipping Carrier Codes:

| SCAC | Carrier Name          | Country | Contact Email      | Active |
|------|-----------------------|---------|--------------------|--------|
| ABCD | ABC Logistics         | USA     | info@abclog.com    | Yes    |
| EFGH | EFG Shipping Co       | USA     | contact@efg.com    | Yes    |
| WXYZ | WXY International     | CAN     | support@wxy.com    | No     |

Configuration:

json
{
  "ExcelGenerations": [
    {
      "SourceFile": "/Sources/scac_codes.xlsx",
      "SheetName": null,
      "Namespace": "Shipping.Data",
      "RootClassName": "ScacCode",
      "StaticClassName": "ScacCodes",
      "KeyColumn": "A",
      "HeaderRowIndex": 1,
      "DataStartRowIndex": 2,
      "ModelType": "RecordStruct",
      "GenerateModelClass": true,
      "GenerateStaticTable": true,
      "GenerateAllCollection": true,
      "ColumnMappings": {
        "SCAC": "Code",
        "Carrier Name": "CarrierName",
        "Contact Email": "Email"
      },
      "PropertyTypeOverrides": {
        "Active": "bool"
      },
      "OutputPath": "./Generated/Shipping/"
    }
  ]
}

Generated Usage:

csharp
using Shipping.Data;

// Lookup by key
var carrier = ScacCodes.ABCD;
Console.WriteLine($"Carrier: {carrier.CarrierName}");

// Search all
var activeCarriers = ScacCodes.All
    .Where(c => c.Active)
    .ToList();

// Use in dropdown
var dropdownItems = ScacCodes.All
    .Select(c => new { Value = c.Code, Label = c.CarrierName })
    .ToList();

Best Practices for Excel Generation ​

  1. Clean Headers: Use clear, descriptive column headers without special characters
  2. Consistent Data Types: Ensure columns contain consistent data types
  3. Key Columns: Use columns with unique values for KeyColumn
  4. Type Overrides: Use PropertyTypeOverrides for enums, custom types, or specific numeric types
  5. Column Mapping: Use ColumnMappings to create clean property names from complex headers
  6. Model Types:
    • Use RecordStruct for small, immutable data
    • Use RecordClass for immutable reference types
    • Use Class for mutable data that needs modification
  7. Output Path: Use OutputPath to organize generated files separately from source code

The generators ​

Nextended.CodeGen is a single Roslyn source generator driven by one CodeGen.config.json (MainConfig). It hosts independent sub-generators, each configured by its own section:

SectionTypeInputProduces
DtoGenerationDtoGenerationConfigYour classes and enums, annotated with [AutoGenerateDto] / [AutoGenerateCom]DTO classes, interfaces, mapping extension methods, COM id class
StructureGenerations[]ClassStructureCodeGenerationConfigA .json or .xml fileStrongly typed classes / records for that structure
ExcelGenerations[]ExcelGenerationConfigAn .xlsx fileA row model plus a static lookup table
CodeToDocs[]CodeToDocsConfigA folder of source files.txt, .md and/or .html documentation
Typescript[]TypescriptGenerationConfigYour compiled types (and the generated DTOs).ts declarations on disk (TypeScript generation)

All sections are optional. An empty {} config file is valid — the DTO generator then runs purely off the attributes.


Documentation generation (CodeToDocs) ​

The fourth generator does not emit C#. It reads source files and writes documentation, which is useful for embedding real, always-current code in a docs site, a Blazor sample browser, or an LLM context bundle.

Configuration ​

json
{
  "CodeToDocs": [
    {
      "DisableGeneration": false,
      "InputFolder": "./Entities",
      "OutputPath": "./Generated/HtmlDocs/",
      "FileIncludePattern": "*.cs",
      "SourceExportTypes": [ "PlainText", "Markdown", "Html" ]
    }
  ]
}
PropertyTypeDefaultPurpose
DisableGenerationboolfalseTurn this entry off without deleting it
InputFolderstring—Folder to scan, relative to the project
OutputPathstring?nullWhere to write. When null, output is added to the compilation instead of the disk
FileIncludePatternstring—Glob applied inside InputFolder, e.g. *.cs, *.razor, *.html
SourceExportTypesSourceExportType[]—Any combination of PlainText (.txt), Markdown (.md), Html (.html)

SourceExportType carries the file extension as a [Description], so the output file name is <source name><extension>.

Output ​

Markdown wraps each file in a fenced block with the right language hint:

markdown
```csharp
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```

Html runs the source through ColorCode, so the result is syntax-highlighted markup you can drop straight into a page. PlainText is a verbatim copy — useful when something else does the formatting.

Multiple entries are allowed, so one project can export its entities as Markdown and its Razor components as HTML in the same build:

json
"CodeToDocs": [
  { "InputFolder": "./Entities",   "FileIncludePattern": "*.cs",    "SourceExportTypes": [ "Markdown" ],     "OutputPath": "./Generated/Docs/Entities/" },
  { "InputFolder": "./Components", "FileIncludePattern": "*.razor", "SourceExportTypes": [ "Html" ],         "OutputPath": "./Generated/Docs/Components/" }
]

COM-visible generation ​

AutoGenerateComAttribute derives from AutoGenerateDtoAttribute with COM-friendly defaults pre-applied:

csharp
public class AutoGenerateComAttribute : AutoGenerateDtoAttribute
{
    public AutoGenerateComAttribute()
    {
        IsComCompatible = true;
        Prefix = "Com";
        Suffix = "";
    }
}

So these two are equivalent:

csharp
[AutoGenerateCom]
public class Address { … }

[AutoGenerateDto(IsComCompatible = true, Prefix = "Com", Suffix = "")]
public class Address { … }

With IsComCompatible = true the generator emits [ComVisible] types with explicit interfaces and stable GUIDs. The GUIDs live in a generated id class so they stay constant across builds — changing them would break registered COM clients.

DTO config propertyDefaultPurpose
ComIdClassName"ComGuids"Name of the generated class holding the GUID constants
ComIdClassPropertyFormat"Id{0}"Format for each constant's name; {0} is the type name
ComIdClassModifierInternalAccessibility of that class (Public, Internal, …)

The sample project has the generated result checked in at Generated/Dtos/ComGuids.g.cs.


Abstract and derived types ​

Domain models are rarely flat. Four DtoGeneration options control what happens at the abstract boundary:

PropertyDefaultEffect
MakeDtoAbstractWhenSourceIsAbstracttrueAn abstract source class produces an abstract DTO — you cannot accidentally instantiate half an object
GenerateToMethodsForAbstractfalseEmit the plain ToDto() methods (which use new) for abstract types. Off by default because new on an abstract type does not compile
GenerateFactoryOverloadsForAbstracttrueEmit ToDto(factory) overloads instead, so the caller supplies the concrete instance
AlwaysGenerateFactoryOverloadsfalseEmit the factory overloads for every type, not only abstract ones
csharp
// Abstract source
[AutoGenerateDto]
public abstract class EntityBase { public Guid Id { get; set; } }

// Generated: abstract DTO + a factory overload
var dto = entity.ToDto(() => new DerivedEntityDto());

On the attribute, AutoGenerateDerived = true additionally generates DTOs for every type derived from the annotated one, so a base class can opt its whole hierarchy in with one attribute. The sample demonstrates this with AnotherBaseWhereDerivedAreAutoGenerated.

Deep properties ​

DeepProperties (default false) controls inherited members. When true, properties of base classes that are not themselves generated are copied into the DTO — otherwise the DTO only carries its own declared properties and relies on a generated base DTO. Turn it on when your base types live in an assembly you cannot annotate.


Mapping generation ​

By default (GenerateMapping = true) the generator emits extension methods in both directions. Names are configurable per type:

csharp
[AutoGenerateDto(ToDtoMethodName = "ToMegaDto", ToSourceMethodName = "AsSrc")]
public class Address : EntityBase { … }
csharp
AddressDto dto = address.ToMegaDto();
Address back = dto.AsSrc();

DefaultMappingSettings sets the names once for the whole project:

json
"DefaultMappingSettings": {
  "MapWithClassMapper": true,
  "ToDtoMethodName": "ToDto",
  "ToSourceMethodName": "ToEntity",
  "Strategy": "Extensions"
}

Strategy (Extensions or Mapperly) is the mapping strategy for every type whose attribute leaves MappingStrategy at Default.

PropertyDefaultEffect
SkipReverseMappingfalseGenerate only source → DTO: no DTO → source AssignTo and no ToSourceMethodName (ToNet/ToEntity) method, for both strategies. For DTOs that are only sent and never written back onto an entity. Enum casts stay in both directions
MapDerivedTypesfalseMapperly only: members typed by a base class map to the DTO of the instance's runtime type, see Derived types with Mapperly
json
"DefaultMappingSettings": { "Strategy": "Mapperly", "ToSourceMethodName": "ToEntity", "SkipReverseMapping": true }

MapWithClassMapper = true routes the property through Nextended.Core's class mapper instead of a direct assignment — which is what you want for a nested complex property whose DTO is generated separately.

Hooking into the mapping ​

Generated mapping code is mechanical, and sooner or later you need one field computed. Rather than editing generated output, opt into partial hooks:

csharp
[AutoGenerateDto(GenerateBeforeAndAfterAssignPartialsInMapping = true)]
public class Address : EntityBase { … }

The generator then emits partial method declarations that run before and after the property assignments. Implement them in your own partial class:

csharp
public partial class AddressDto
{
    partial void BeforeAssign(Address source) { … }
    partial void AfterAssign(Address source)
    {
        FullAddress = $"{Street} {Number}, {City}";
    }
}

GenerateBeforeAndAfterAssignPartialsInMappingAttribute applies the same thing at class level for sources you configure elsewhere. The sample keeps its hand-written partial next to the entities in Entities/Partials/AdressDto.cs.

Mapperly instead of extension methods ​

Every type can choose how its mapping is generated. MappingStrategy = DtoMappingStrategy.Mapperly generates a partial Riok.Mapperly mapper instead of the MappingExtensions methods; DefaultMappingSettings.Strategy sets it for all types that leave the attribute at Default.

csharp
[AutoGenerateDto(MappingStrategy = DtoMappingStrategy.Mapperly)]
public class Product : EntityBase { … }
csharp
// ProductMapper.g.cs (generated)
[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)]
[UseStaticMapper(typeof(MyApp.Mapping.MappingExtensions))]   // nested DTO types reuse their own mapping
public static partial class ProductMapper
{
    public static partial ProductDto ToDto(this Product src);
    [MapperIgnoreTarget("TenantId")]                           // source members the DTO does not carry
    public static partial Product ToNet(this ProductDto src);
    public static partial void AssignTo(this Product src, [MappingTarget] ProductDto dest);
    [MapperIgnoreTarget("TenantId")]
    public static partial void AssignTo(this ProductDto src, [MappingTarget] Product dest);
}

Call sites stay the same as with the default strategy (product.ToDto()). Mapperly implements the methods at compile time, so add the package to the project that holds the entities:

xml
<PackageReference Include="Riok.Mapperly" PrivateAssets="all" ExcludeAssets="runtime" />

Overriding. The mapper is partial. Whatever you declare in your own part of the class wins and is left out of the generated part — matched by method name (AssignTo covers both directions), and a [Mapper] attribute on your part replaces the generated one:

csharp
public static partial class ProductMapper
{
    [MapProperty(nameof(Product.Rate), nameof(ProductDto.Rate), Use = nameof(RoundRate))]
    public static partial ProductDto ToDto(this Product src);

    [UserMapping(Default = false)]
    private static decimal RoundRate(decimal rate) => Math.Round(rate, 2);
}

Files on disk. Source generators do not see each other's output, so Mapperly can only implement a mapper that exists as a real file. The Mapperly strategy therefore needs OutputPath (the DTOs) and MappingOutputPath (or OutputPath) — without them the generated mapper contains an #error that says so. Like every file written to disk, a change to the entity shows up after the next build.

Enums, generic and abstract types always use the extension methods (an abstract type additionally gets a Mapperly mapper with MapDerivedTypes, below).

Derived types with Mapperly ​

Mapperly cannot create an abstract DTO, so a member typed by an abstract class (Document? Main, List<Document> Documents) does not map without help, and a member typed by a concrete base class maps only the base members. DefaultMappingSettings.MapDerivedTypes = true emits Mapperly's MapDerivedType for every concrete type below it that has a Mapperly mapper, most derived first:

csharp
[AutoGenerateDto(AutoGenerateDerived = true)]
public abstract class Document { public string? Name { get; set; } }
public class Invoice : Document { public decimal Total { get; set; } }
public class CreditNote : Invoice { public string? Reason { get; set; } }

[AutoGenerateDto]
public class Shipment { public Document? Main { get; set; } public List<Document> Documents { get; set; } = new(); }
csharp
// DocumentMapper.g.cs (generated, only for abstract types that a DTO carries as a member)
[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)]
[UseStaticMapper(typeof(MyApp.Mapping.CreditNoteMapper))]
[UseStaticMapper(typeof(MyApp.Mapping.InvoiceMapper))]
public static partial class DocumentMapper
{
    [MapDerivedType(typeof(CreditNote), typeof(CreditNoteDto))]
    [MapDerivedType(typeof(Invoice), typeof(InvoiceDto))]
    public static partial DocumentDto ToDto(this Document src);
    [MapDerivedType(typeof(CreditNoteDto), typeof(CreditNote))]
    [MapDerivedType(typeof(InvoiceDto), typeof(Invoice))]
    public static partial Document ToNet(this DocumentDto src);
}

// InvoiceMapper.g.cs: a concrete base type gets the attributes on its own methods
[MapDerivedType(typeof(CreditNote), typeof(CreditNoteDto))]
public static partial InvoiceDto ToDto(this Invoice src);

ShipmentMapper then uses DocumentMapper for Main and Documents, and shipment.ToDto().Main is a CreditNoteDto when the document is a credit note. The extension methods of the abstract type (AssignTo, the factory overloads) are generated as before.

Generic types ​

Generic sources stay generic, and a type with a generated DTO is replaced by that DTO wherever it appears as a type argument:

SourceGenerated
member Dimension<WeightUnit> WeightDimensionDto<WeightUnitDto> Weight
base class class AddressHolder : Holder<Address>class AddressHolderDto : HolderDto<AddressDto> (and IHolderDto<AddressDto>)
constraint class Dimension<TUnit> where TUnit : Unitclass DimensionDto<TUnit> where TUnit : UnitDto

This holds for types marked through a base's AutoGenerateDerived too (where TUnit : WeightUnit becomes WeightUnitDto when WeightUnit gets its DTO only because Unit has AutoGenerateDerived = true).

Mapping a generic type. When a type parameter is constrained to a type with a DTO, the entity side and the DTO side need different type arguments (Dimension<WeightUnit> and DimensionDto<WeightUnitDto>), so the extension methods get a second type parameter for the DTO side. Members of that type parameter are mapped by Nextended.Core's class mapper:

csharp
public static void AssignTo<TUnit, TUnitDto>(this Dimension<TUnit> src, DimensionDto<TUnitDto> dest)
    where TUnit : Unit where TUnitDto : UnitDto
{
    dest.Value = src.Value;
    dest.Unit = src.Unit?.MapTo<TUnitDto>();
}

var dto = dimension.ToDto<WeightUnit, WeightUnitDto>();   // AssignTo infers both from its arguments

Type parameters without such a constraint keep one parameter list, as before (AssignTo<T>(this Item<T> src, ItemDto<T> dest)). A type with a constructed generic base (class NumberHolder : Holder<int>) calls the base's AssignTo first, so the base members are mapped. When a base type argument has a DTO and the base's type parameter has no DTO counterpart (Holder<Address> with an unconstrained T), the extension methods leave the base members out; the Mapperly strategy maps them, because the mapper of the non-generic type sees the closed members.

Enums ​

A generated enum carries its members and values. Its attributes are opt-in:

SettingWhereEffect
KeepEnumFlagsAndUnderlyingTypeDtoGeneration[Flags] and the underlying type (: short) of the source enum
KeepAttributesOnGeneratedClassthe enum's [AutoGenerateDto]every attribute of the source enum ([Flags], [Description], ...)
PreClassStringthe enum's [AutoGenerateDto]text written above the enum, e.g. a JSON converter
csharp
[Flags]
[AutoGenerateDto(PreClassString = "[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]")]
public enum ShipmentState : short { None = 0, Booked = 1, Delayed = 2 }

// with "KeepEnumFlagsAndUnderlyingType": true
[System.Flags]
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
public enum ShipmentStateDto : short { None = 0, Booked = 1, Delayed = 2 }

The PreClassString of the configuration is not written above enums, it is meant for classes.

Collections start empty ​

InitializeCollections = true initializes the collection properties of generated classes and records that are not nullable (arrays, List, IList, ICollection, IEnumerable, IReadOnlyList, IReadOnlyCollection, HashSet, Dictionary) with [], so a DTO created with new or by a deserializer that skips missing members has empty lists instead of null:

csharp
public System.Collections.Generic.List<LineDto> Lines { get; set; } = [];
public System.Collections.Generic.List<int>? Maybe { get; set; }          // nullable: left as it is

[] needs C# 12. Struct model types are left out.

Leaving types out ​

TypesToIgnore lists types that get no DTO, by name or namespace-qualified name without generic arguments. A listed type also takes out the types derived from it that come in only through a base's AutoGenerateDerived; a derived type with an [AutoGenerateDto] of its own is generated still:

json
"TypesToIgnore": [ "BaseServiceConnector", "MyApp.Domain.ListDataConversion" ]

A member whose type is left out keeps the source type; leave such members out as well ([IgnoreOnGeneration], PropertiesToIgnore).

Ignoring properties everywhere ​

PropertiesToIgnore in the DtoGeneration section applies to every type whose attribute does not set its own list — handy for columns such as TenantId or audit fields that no DTO should carry. Source properties declared required stay required on the DTO, and the generated mapping sets them when it creates an instance.

DTO views: several DTOs of one entity ​

The first [AutoGenerateDto] on a type describes its default DTO. Every further [AutoGenerateDto] on the same type generates one more DTO of it, a view: another shape for another client (an older API, a list row, an export), next to the default DTO and with its own mapping. A type with a single attribute generates exactly what it generated before.

csharp
[AutoGenerateDto(AutoGenerateDerived = true)]                       // default: QuotationDto
[AutoGenerateDto(GeneratedClassName = "QuotationAbp",               // view: QuotationAbpDto
    PropertyNames = ["DateCreatedUtc=CreationTime", "DateUpdatedUtc=LastModificationTime"],
    UseViews = ["PortAbp", "HubCode", "QuotationStatusAbp"],
    PropertiesToIgnore = ["InternalNote"])]
public class Quotation : GuidBaseEntity
{
    public string QuoteNumber { get; set; } = "";
    public QuotationStatus Status { get; set; }
    public Port? PortOriginRequested { get; set; }
    public Incoterm? IncoTerm { get; set; }
    public List<Port> Stops { get; set; } = [];
    public string? InternalNote { get; set; }
}

// 16 members, the view keeps 8
[AutoGenerateDto(AutoGenerateDerived = true)]
[AutoGenerateDto(GeneratedClassName = "PortAbp", PropertiesToIgnore = ["DateCreatedUtc", "DateUpdatedUtc", "Country",
    "IsRailTerminal", "IsRoadTerminal", "IsPostalOffice", "IsBorder", "ExternalIds"])]
public class Port : GuidBaseEntity { /* ... */ }

// one view for every code entity: declared on their common base
[AutoGenerateDto(AutoGenerateDerived = true)]
[AutoGenerateDto(GeneratedClassName = "HubCode", PropertiesToIgnore = ["DateCreatedUtc", "DateUpdatedUtc", "CargonerdsCustomerId"])]
public abstract class CodeEntity : GuidBaseEntity { /* Code, Description, CargonerdsCustomerId, IsVisibleInSpark */ }

// the default enum DTO is sent by name, the view by number
[AutoGenerateDto(PreClassString = "[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]")]
[AutoGenerateDto(GeneratedClassName = "QuotationStatusAbp")]
public enum QuotationStatus { Draft, Requested, Quoted }
csharp
// generated
public partial class QuotationAbpDto : IQuotationAbpDto
{
    public string QuoteNumber { get; set; }
    public Shop.Contracts.QuotationStatusAbpDto Status { get; set; }       // no string converter: a number in JSON
    public Shop.Contracts.PortAbpDto? PortOriginRequested { get; set; }
    public Shop.Contracts.HubCodeDto? IncoTerm { get; set; }               // the view of the base CodeEntity
    public System.Collections.Generic.List<Shop.Contracts.PortAbpDto> Stops { get; set; }
    public System.Guid Id { get; set; }
    public System.DateTimeOffset CreationTime { get; set; }                // inherited DateCreatedUtc, renamed
    public System.DateTimeOffset LastModificationTime { get; set; }
}

var abp = quotation.ToQuotationAbpDto();   // the default stays quotation.ToDto()

How a view behaves:

NameGeneratedClassName is required; it is also the view's key that UseViews and GenerationPropertySetting.View name. The class name gets the view's Prefix/Suffix as usual (QuotationAbp → QuotationAbpDto)
Membersall public instance properties, inherited ones included (also without DeepProperties), minus its own PropertiesToIgnore (which replaces the configuration's list, as for every DTO) and [IgnoreOnGeneration] members
Shapeflat: no base DTO, an interface I<View> and a class like every DTO; concrete also when the type is abstract. BaseType, Interfaces, PreClassString, Namespace come from the view's attribute, else from the configuration
Settings per viewevery setting of [AutoGenerateDto] applies to the view alone: Namespace, PropertiesToIgnore, GenerateMapping, MappingStrategy, ToDtoMethodName, ToSourceMethodName, IsComCompatible, KeepPropertyAttributesOn..., PreClassString (an enum view takes only its own), OutputPath
Not inheritedAutoGenerateDerived types do not get the views of their base; a member typed by a derived type uses the base's view through UseViews
Files<View>.g.cs (one file per view also with OneFilePerClass = false), MappingExtensions.g.<Type>.<View>.cs or <View>Mapper.g.cs

Member renames — PropertyNames holds "SourceName=DtoName" pairs. Unlike [GenerationPropertySetting(PropertyName = ...)], which sits on the property and therefore renames it in every DTO that carries it, PropertyNames belongs to one DTO and reaches inherited members too. It wins over PropertyName. On a default DTO it renames the members that DTO declares itself (inherited members live in the base DTO).

Member types — a member whose type has a DTO gets the type's default DTO. UseViews lists view keys: a member whose type declares one of them, or whose base type does, gets that view's type and mapping instead (Port → PortAbpDto, Incoterm → HubCodeDto). This also works inside collections and on default DTOs. A view's members typed by the view's own type stay in the view (Node.Parent → NodeRowDto); types of the DTO's own hierarchy (its base and derived types) never switch to a view.

One view for many entities — several entities share one view type by declaring it once on a common base type (HubCodeDto on CodeEntity above): the view has the base's members, its mapping ToHubCodeDto(this CodeEntity) takes every derived entity. Unrelated entities that declare the same view name do not merge into one type; the second one is reported (NCG011) and left out.

Property settings per view — [GenerationPropertySetting] may be applied more than once. A setting with View = "<key>" replaces the setting without View for that view; the setting without View applies to the default DTO and to every view without its own:

csharp
[GenerationPropertySetting(PreClassString = "[FacetDisplay(Displays.Port)]")]   // default DTO and other views
[GenerationPropertySetting(View = "OrderRow", PropertyName = "No")]             // the OrderRow view: renamed, no attribute
public string Number { get; set; }

Mapping — each view gets its own mapping with the view's strategy: To<ViewClass>() (e.g. ToQuotationAbpDto()) unless the view sets ToDtoMethodName (the configuration's DefaultMappingSettings.ToDtoMethodName is for default DTOs), AssignTo overloads, and back (ToNet/ToSourceMethodName) unless SkipReverseMapping is set. With Mapperly the mapper is <ViewClass>Mapper and nested views are used through [UseStaticMapper]. A view of an abstract type maps only towards the view; a member mapped through a view of a base type (IncoTerm → HubCodeDto) is skipped when mapping back (// skipped 'IncoTerm': the view HubCodeDto cannot create a Incoterm).

Diagnostics — mistakes are reported, never silently ignored:

IdSeverityWhen
NCG010warninga further [AutoGenerateDto] without GeneratedClassName (not generated)
NCG011errorthe view's type name is already generated (by the default DTO, another view or another entity); the view is left out
NCG012errorthe view's mapping method is already used by another DTO of the type; set ToDtoMethodName
NCG013warningUseViews names a key no generated type declares
NCG014warninga PropertyNames entry is not Source=Dto or names no property of the type

The view settings (PropertyNames, UseViews, OutputPath, GenerationPropertySetting.View) are read by name, so the generator needs no particular Nextended.Core version; your project needs a Nextended.Core that declares them to compile the attributes. Views that use only the other settings (GeneratedClassName, PropertiesToIgnore, Namespace, ...) work with any version — the CodeGenSample shows one (AddressLine on Address), the tests in DtoViewTests cover the example above end to end (extensions and Mapperly, JSON, diagnostics).

Where the files land ​

PropertyDefaultEffect
OutputPathnullWhere DTOs go. null = added to the compilation, nothing on disk
MappingOutputPathnullSeparate destination for the mapping files (falls back to OutputPath)
PropertiesToIgnorenullProperty names left out of every DTO whose attribute has no own list
OneFilePerClasstrueOne file per generated type instead of one combined file
CreateFileHeaderstrueEmit the auto-generated header comment
CreateRegionstrueWrap sections in #region blocks
CreateCommentstrueCarry XML documentation over to the generated members
GeneratePartialtrueGenerate partial types so you can extend them
DeleteStaleFilesfalseDelete files of earlier runs that this run no longer writes (see below)
GeneratedCodeAttributetrue[GeneratedCode("Nextended.CodeGen", null)] on every generated type, see Generated code marker
GeneratedCodeVersionfalsethe generator's package version in that attribute instead of null

Writing to OutputPath puts the generated code in your repository rather than in obj/. That makes review diffs meaningful and lets you inspect what the generator actually produced — which is why the sample project checks its output in.

Stale files. The generator overwrites what it writes, but it never deleted a file it no longer writes (a removed entity, a renamed view): the old file stays and is still compiled. With "DeleteStaleFiles": true (json DtoGeneration) or Defaults(d => d.DeleteStaleFiles()) each run deletes, in every folder the DTO generation writes to in that run (OutputPath, MappingOutputPath, views' and DTOs' own OutputPath), the .cs files that

  • this run did not write (no generator of the run wrote them), and
  • start with the generator's header line // <auto-generated/> (every DTO, view, mapping and ComGuids file has it, also with CreateFileHeaders(false)).

Nothing else is touched: no hand-written file, no file of another tool (// <auto-generated /> with a space, Emit files without the header line), no subfolder, no folder the run does not write to (a views folder whose last view is gone keeps its files). The cleanup is skipped while the project has syntax errors or the fluent configuration has an NCG020 error (the IDE runs the generator on every keystroke; a half-typed Dto<T>() must not delete the file), and when the DTO generation fails. Because the folder decides, give every project its own output folders: two projects writing DTOs into the same folder would delete each other's files. With the compiler server (the default), a run only happens when the inputs change; a stale file therefore goes with the next real change or a rebuild.

Generated code marker ​

Every type the generators write carries [global::System.CodeDom.Compiler.GeneratedCode("Nextended.CodeGen", null)]: DTO classes and records, their interfaces, enums, Mapperly mapper classes, the ComGuids class, the classes of StructureGenerations and ExcelGenerations (model and table) and the facet registration. Analyzers, code coverage and code metrics then treat them as generated, and the TypeScript generation can select them in other projects (IncludeTypesWithAttributes). The line sits right below the XML comment, above the other attributes:

csharp
[global::System.CodeDom.Compiler.GeneratedCode("Nextended.CodeGen", null)]
public partial class OrderDto : IOrderDto
  • Not written twice: a type that keeps its source attributes (KeepAttributesOnGeneratedClass/...Interface) and has a [GeneratedCode] there, or whose PreClassString/PreInterfaceString contains one, gets no second one.
  • The mapping extension class (MappingExtensions) gets none: it is one partial class spread over a file per type, and the attribute may appear only once per type.
  • Upgrading writes it once into every generated file (one line per type), a one-time diff of checked-in generated files. To keep the files as they are, switch it off: json "GeneratedCodeAttribute": false (DtoGeneration, and per entry of StructureGenerations/ ExcelGenerations), fluent Defaults(d => d.GeneratedCodeAttribute(false)), StructureGeneration(s => s.GeneratedCodeAttribute(false)), ExcelGeneration(e => e.GeneratedCodeAttribute(false)). The DTO setting also covers mappers and the facet registration.
  • GeneratedCodeVersion(true) (json "GeneratedCodeVersion": true) writes the generator's package version ("10.1.64") instead of null. Off by default: with it every package update changes every generated file.

The mapping files share one namespace (the configuration's Namespace), while a DTO or view can have a Namespace of its own. Generated code names such a DTO with its namespace wherever the file lives in another one, also in generic constraints (where TUnitDto : global::MyApp.Contracts.Hub.HubCodeDto) and in the casts to a base DTO; no global using or alias is needed for it.


Walkthrough: the CodeGenSample project ​

Tests/TestProjects/CodeGenSample exercises all four generators and has every generated file committed, so you can read the input and the output side by side without running a build.

CodeGenSample/
├─ CodeGen.config.json            all four sections configured
├─ Entities/
│  ├─ Address.cs                  [AutoGenerateDto] with custom method names + COM
│  ├─ User.cs                     attribute retention, ignored members, renamed properties
│  ├─ AbstractClasses.cs          abstract + AutoGenerateDerived
│  ├─ GenericBaseClass.cs         generic sources
│  ├─ Base/                       EntityBase, interfaces
│  ├─ Enums/UserLevel.cs          enum → DTO enum
│  └─ Partials/AdressDto.cs       hand-written partial extending a generated DTO
├─ Sources/
│  ├─ appsettings.json            input for StructureGenerations
│  └─ scac_codes.xlsx             input for ExcelGenerations
└─ Generated/                     committed output
   ├─ Dtos/                       19 generated DTOs + ComGuids.g.cs
   ├─ Extensions/                 MappingExtensions.g.<Type>.cs, one per source type
   ├─ AppSettings/appsettings.g.cs
   ├─ Excel/scac_codes.row.g.cs + scac_codes.table.g.cs
   └─ HtmlDocs/                   CodeToDocs output

Wiring it up ​

The generator needs two things: the package reference, and the config file registered as an AdditionalFiles item so Roslyn hands it to the analyzer.

xml
<ItemGroup>
  <PackageReference Include="Nextended.Core" Version="10.1.22"
                    PrivateAssets="all" GeneratePathProperty="true" />
  <PackageReference Include="Nextended.CodeGen" Version="10.1.22" />
</ItemGroup>

<ItemGroup>
  <AdditionalFiles Include="CodeGen.config.json" />
</ItemGroup>

Nextended.Core carries the attributes. PrivateAssets="all" keeps it out of your own package's dependencies when the attributes are only used at build time.

Input → output, one property at a time ​

Entities/User.cs in the sample:

csharp
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
[AutoGenerateDto(Prefix = "My", Suffix = "Dto", IsComCompatible = false,
    KeepAttributesOnGeneratedClass = true,
    AddContainingNamespaceUsings = true,
    DefaultPropertyInterfaceAccess = InterfaceProperty.Get,
    KeepPropertyAttributesOnGeneratedClass = true,
    KeepPropertyAttributesOnGeneratedInterface = true)]
public class User : EntityBase
{
    [MaxLength(3)]
    public string Name { get; set; }

    [IgnoreOnGeneration]
    public string SecretDb { get; set; }

    [GenerationPropertySetting(PropertyName = "ThatUserAddress", MapWithClassMapper = true)]
    public Address Address { get; set; }

    [GenerationPropertySetting(PropertyName = "UserLevel", InterfaceAccess = InterfaceProperty.GetAndSet)]
    public UserLevel? Level { get; set; }
}

What each line does to the output — see Generated/Dtos/MyUserDto.g.cs:

InputResult
Prefix = "My", Suffix = "Dto"Type is named MyUserDto
KeepAttributesOnGeneratedClass[JsonNumberHandling(...)] is copied onto MyUserDto
KeepPropertyAttributesOnGeneratedClass[MaxLength(3)] survives on Name
[IgnoreOnGeneration] on SecretDbThe property does not exist on the DTO at all
PropertyName = "ThatUserAddress"Address is exposed as ThatUserAddress
MapWithClassMapper = trueThe nested Address is mapped by the class mapper, not assigned directly
DefaultPropertyInterfaceAccess = GetThe generated interface exposes get-only properties …
InterfaceAccess = GetAndSet on Level… except UserLevel, which is settable
AddContainingNamespaceUsingsA using for the source namespace is emitted

PropertiesToIgnore on the attribute is the alternative to [IgnoreOnGeneration] for source types you cannot edit.

Running it ​

bash
git clone https://github.com/fgilde/Nextended.git
cd Nextended/Tests/TestProjects/CodeGenSample
dotnet build

Because the sample writes to OutputPath, a build regenerates the files under Generated/. Run git diff afterwards to see exactly what the generator produced — an effective way to understand a config change, and a reasonable regression check to keep in CI.

Generation without an output path (in memory) ​

When OutputPath is null (json, attribute or fluent), generated code goes into the compilation only, nothing is written to disk.

  • Direction. The generated types exist in the project that runs the generator and in the projects that reference it, nowhere else. A source generator can add code only to the compilation it runs in; it cannot write into another project. To have the DTOs in a contracts project, run the generation in that project (it references the entities), or set OutputPath to a folder of that project (a relative path such as ../MyApp.Contracts/Dtos/).
  • File names. The files keep the names they would have on disk. When a run produces two files with the same name (OfferDto in A.Contracts and in B.Contracts), the first keeps its name and a later one is added as <namespace>.<file name> (B.Contracts.OfferDto.g.cs), then with a number. Only the name of the added source changes, never a namespace or a class; with OutputPath the names on disk are not affected.
  • Mapperly. The Mapperly strategy needs OutputPath and MappingOutputPath: Mapperly does not see code another source generator adds, so without them the mapper file holds an #error (see Mapperly instead of extension methods). The extension methods work in memory.
  • TypeScript. The TypeScript generation reads the compilation without generated code, so IncludeNamespaces, IncludeTypes and IncludeBaseTypes do not find in-memory DTOs. FromGeneratedDtos: true (fluent FromGeneratedDtos()) takes them, see TypeScript generation.
  • Seeing the code. In Visual Studio under Dependencies > Analyzers > Nextended.CodeGen > Nextended.CodeGen.MainGenerator, in Rider under Dependencies > Source Generators, or as files with:
xml
<PropertyGroup>
  <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
  <CompilerGeneratedFilesOutputPath>GeneratedFiles</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

Both lines are present, commented out, in the sample's .csproj. The emitted files are a copy for reading; the compilation does not use them.

Best Practices ​

1. Use Meaningful Names ​

csharp
[AutoGenerateDto(
    Namespace = "MyApp.Api.Dtos",
    ToDtoMethodName = "ToApiDto",
    ToSourceMethodName = "ToEntity"
)]
public class User { }

2. Organize Generated Code ​

json
{
  "DtoGeneration": {
    "Namespace": "MyApp.Generated.Dtos",
    "OutputPath": "./Generated/Dtos/",
    "OneFilePerClass": true
  }
}

3. Version Control Generated Files ​

Add to .gitignore if you regenerate on build, or commit them if you want to review changes.

4. Use Partial Classes for Customization ​

Generated as partial classes allow you to extend:

csharp
// Generated
public partial class UserDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// Your custom code
public partial class UserDto
{
    public string DisplayName => $"User: {Name}";
}

Attribute Reference ​

AutoGenerateDtoAttribute ​

The AutoGenerateDtoAttribute is the primary attribute for generating DTOs from your classes. It provides extensive configuration options to control the generated code.

Properties ​

Namespace Configuration ​
csharp
[AutoGenerateDto(Namespace = "MyApp.Dtos")]
public class User { }

Namespace (string?)
Sets the namespace for the generated DTO. If not specified, uses the configuration file default or the source class namespace with a "Dto" suffix.

Naming Configuration ​
csharp
[AutoGenerateDto(
    Prefix = "Api",
    Suffix = "Response",
    GeneratedClassName = "CustomUserName"  // Overrides prefix/suffix
)]
public class User { }
// Generates: ApiUserResponse or CustomUserName

Prefix (string?)
Adds a prefix to the generated class name. Default: empty string.

Suffix (string?)
Adds a suffix to the generated class name. Default: "Dto".

GeneratedClassName (string?)
Explicitly sets the generated class name, overriding prefix and suffix logic. Required on every further [AutoGenerateDto] of a type, which generates a DTO view; there it is also the view's key.

PropertyNames (string[]?)
"SourceName=DtoName" pairs that rename members of this DTO, inherited ones included. Wins over GenerationPropertySetting.PropertyName.

UseViews (string[]?)
Keys of DTO views: a member whose type (or a base of it) declares one of them gets that view instead of the default DTO.

OutputPath (string?)
Output path of this DTO's file; overrides DtoGeneration.OutputPath.

Property Filtering ​
csharp
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    
    [IgnoreOnGeneration]
    public string Password { get; set; }  // Excluded from DTO
}

// Alternative: Configure in attribute
[AutoGenerateDto(PropertiesToIgnore = new[] { "Password", "InternalId" })]
public class User 
{
    public string Password { get; set; }
    public string InternalId { get; set; }
}

PropertiesToIgnore (string[])
Array of property names to exclude from the generated DTO.

Mapping Configuration ​
csharp
[AutoGenerateDto(
    GenerateMapping = true,
    ToDtoMethodName = "ToUserDto",
    ToSourceMethodName = "ToUser"
)]
public class User { }

// Usage
var user = GetUser();
var dto = user.ToUserDto();
var userAgain = dto.ToUser();

GenerateMapping (bool)
When true, generates extension methods for mapping between source and DTO. Default: true.

ToDtoMethodName (string?)
Name of the method that converts source to DTO. Default: "ToDto".

ToSourceMethodName (string?)
Name of the method that converts DTO back to source. Default: "ToSource".

COM Compatibility ​
csharp
[AutoGenerateDto(IsComCompatible = true)]
public class User { }

IsComCompatible (bool)
Generates COM-visible classes with appropriate attributes and GUIDs. Used for COM interop scenarios.

Type Configuration ​
csharp
[AutoGenerateDto(
    BaseType = "EntityBase",
    Interfaces = new[] { "IEntity", "IAuditable" }
)]
public class User { }

// Generates:
public class UserDto : EntityBase, IEntity, IAuditable { }

BaseType (string?)
Sets the base class for the generated DTO.

Interfaces (string[]?)
Adds interfaces that the generated DTO should implement.

Modifiers ​
csharp
[AutoGenerateDto(
    ClassModifier = Modifier.Internal,
    InterfaceModifier = Modifier.Public
)]
public class User { }

ClassModifier (Modifier)
Access modifier for the generated class. Options: Unset, Public, Private, Protected, Internal.

InterfaceModifier (Modifier)
Access modifier for the generated interface (if applicable).

DefaultPropertyInterfaceAccess (InterfaceProperty)
Default accessor type for interface properties. Options: Unset, GetAndSet, Get, Set.

Using Directives ​
csharp
[AutoGenerateDto(
    Usings = new[] { "System.Text.Json.Serialization", "MyApp.CustomTypes" },
    AddReferencedNamespacesUsings = true,
    AddContainingNamespaceUsings = true
)]
public class User { }

Usings (string[]?)
Additional using directives to include in the generated file.

AddReferencedNamespacesUsings (bool)
Automatically includes using directives for all referenced types.

AddContainingNamespaceUsings (bool)
Includes using directive for the source class's namespace.

Custom Code Injection ​
csharp
[AutoGenerateDto(
    PreInterfaceString = "[JsonObject]",
    PreClassString = "[Serializable]\n[DataContract]"
)]
public class User { }

// Generates:
[JsonObject]
public interface IUserDto { }

[Serializable]
[DataContract]
public class UserDto { }

PreInterfaceString (string?)
Code to insert before the generated interface declaration (e.g., attributes).

PreClassString (string?)
Code to insert before the generated class declaration (e.g., attributes).

Attribute Preservation ​
csharp
[AutoGenerateDto(
    KeepAttributesOnGeneratedClass = true,
    KeepAttributesOnGeneratedInterface = true,
    KeepPropertyAttributesOnGeneratedClass = true,
    KeepPropertyAttributesOnGeneratedInterface = true
)]
[DataContract]
public class User 
{
    [Required]
    [DataMember]
    public string Name { get; set; }
}

// Generated DTO keeps the attributes
[DataContract]
public class UserDto 
{
    [Required]
    [DataMember]
    public string Name { get; set; }
}

KeepAttributesOnGeneratedClass (bool)
Copies class-level attributes from source to generated class.

KeepAttributesOnGeneratedInterface (bool)
Copies class-level attributes from source to generated interface.

KeepPropertyAttributesOnGeneratedClass (bool)
Copies property-level attributes from source properties to generated class properties.

KeepPropertyAttributesOnGeneratedInterface (bool)
Copies property-level attributes from source properties to generated interface properties.

Derived Type Generation ​
csharp
[AutoGenerateDto(AutoGenerateDerived = true)]
public class BaseEntity { }

public class User : BaseEntity { }  // DTO automatically generated
public class Product : BaseEntity { }  // DTO automatically generated

AutoGenerateDerived (bool)
Automatically generates DTOs for all derived types when applied to a base class.

IgnoreOnGenerationAttribute ​

Use this attribute to exclude specific properties or fields from DTO generation.

csharp
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    
    [IgnoreOnGeneration]
    public string Password { get; set; }
    
    [IgnoreOnGeneration]
    public byte[] PasswordHash { get; set; }
}

GenerationPropertySettingAttribute ​

Fine-tune individual property generation with this attribute.

csharp
public class User
{
    public int Id { get; set; }
    
    [GenerationPropertySetting(
        PropertyName = "FullName",  // Rename in DTO
        MapWithClassMapper = true,   // Use ClassMapper for conversion
        InterfaceAccess = InterfaceProperty.Get,  // Read-only in interface
        PreClassString = "[JsonProperty(\"full_name\")]",
        KeepAttributesOnGeneratedClass = true
    )]
    public string Name { get; set; }
}

// Generated:
public interface IUserDto
{
    string FullName { get; }  // Read-only
}

public class UserDto : IUserDto
{
    [JsonProperty("full_name")]
    public string FullName { get; set; }
}

Properties:

  • PropertyName (string?) - Custom name for the property in the generated DTO
  • View (string?) - The DTO view (its GeneratedClassName) the setting is for. The attribute may be applied several times; a setting for a view replaces the one without View there
  • MapWithClassMapper (bool) - Use ClassMapper for type conversion during mapping
  • InterfaceAccess (InterfaceProperty) - Property accessor type in interfaces (Get, Set, or GetAndSet)
  • PreInterfaceString (string?) - Code to insert before the property in the interface
  • PreClassString (string?) - Code to insert before the property in the class
  • KeepAttributesOnGeneratedClass (bool) - Keep property attributes in generated class
  • KeepAttributesOnGeneratedInterface (bool) - Keep property attributes in generated interface

Complete Example: Advanced DTO Generation ​

csharp
using Nextended.Core.Attributes;
using Nextended.Core.Enums;

namespace MyApp.Domain
{
    /// <summary>
    /// User entity with complete DTO generation configuration
    /// </summary>
    [AutoGenerateDto(
        Namespace = "MyApp.Dtos",
        Suffix = "Response",
        ToDtoMethodName = "ToUserResponse",
        ToSourceMethodName = "ToUserEntity",
        GenerateMapping = true,
        BaseType = "AuditableDto",
        Interfaces = new[] { "IUserResponse", "IIdentifiable" },
        Usings = new[] { "System.Text.Json.Serialization" },
        ClassModifier = Modifier.Public,
        PreClassString = "[JsonSerializable(typeof(UserResponse))]",
        KeepPropertyAttributesOnGeneratedClass = true,
        PropertiesToIgnore = new[] { "PasswordHash", "PasswordSalt" }
    )]
    public class User
    {
        public int Id { get; set; }
        
        [Required]
        [MaxLength(100)]
        public string UserName { get; set; }
        
        [Required]
        [EmailAddress]
        public string Email { get; set; }
        
        [GenerationPropertySetting(
            PropertyName = "FullName",
            PreClassString = "[JsonPropertyName(\"fullName\")]"
        )]
        public string Name { get; set; }
        
        [IgnoreOnGeneration]
        public byte[] PasswordHash { get; set; }
        
        [IgnoreOnGeneration]
        public byte[] PasswordSalt { get; set; }
        
        public DateTime CreatedAt { get; set; }
        public DateTime? ModifiedAt { get; set; }
        
        public List<Address> Addresses { get; set; }
    }
    
    [AutoGenerateDto(
        Namespace = "MyApp.Dtos",
        Suffix = "Response"
    )]
    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
    }
}

Generated result:

csharp
namespace MyApp.Dtos
{
    using System;
    using System.Collections.Generic;
    using System.Text.Json.Serialization;
    using System.ComponentModel.DataAnnotations;
    
    [JsonSerializable(typeof(UserResponse))]
    public class UserResponse : AuditableDto, IUserResponse, IIdentifiable
    {
        [Required]
        [MaxLength(100)]
        public string UserName { get; set; }
        
        [Required]
        [EmailAddress]
        public string Email { get; set; }
        
        [JsonPropertyName("fullName")]
        public string FullName { get; set; }
        
        public DateTime CreatedAt { get; set; }
        public DateTime? ModifiedAt { get; set; }
        
        public List<AddressResponse> Addresses { get; set; }
    }
    
    public class AddressResponse
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
    }
}

Usage:

csharp
var user = await _userRepository.GetByIdAsync(userId);
var response = user.ToUserResponse();
return Ok(response);

Troubleshooting ​

Generated Code Not Appearing ​

  1. Ensure CodeGen.config.json is marked as AdditionalFiles
  2. Clean and rebuild: dotnet clean && dotnet build
  3. Check build output for generator messages
  4. Verify source generators are enabled in IDE

Build Errors After Generation ​

  1. Check namespace conflicts
  2. Verify property types are valid
  3. Ensure all dependencies are installed

Supported Frameworks ​

  • .NET Standard 2.0 (Generator)
  • .NET 8.0+ (Generated code)

Dependencies ​

  • Roslyn APIs for source generation
  • Nextended.Core for attributes

Sample Project ​

See the CodeGenSample project for complete examples.