Skip to content

Custom File‐Based Templates

Simon Hughes edited this page Mar 20, 2026 · 1 revision

File-based templates let you store your Mustache templates on disk and customize them independently of the generator version. This is useful when you want full control over the generated code and want changes to persist across generator upgrades.

Activation

Set TemplateType to a FileBased variant matching your target EF version:

Settings.TemplateType = TemplateType.FileBasedCore10; // EF Core 10
Settings.TemplateType = TemplateType.FileBasedCore9;  // EF Core 9
Settings.TemplateType = TemplateType.FileBasedCore8;  // EF Core 8
Settings.TemplateType = TemplateType.FileBasedEf6;    // EF 6

Also set the GeneratorType to match:

Settings.GeneratorType = GeneratorType.EfCore; // For EfCore 8/9/10
Settings.GeneratorType = GeneratorType.Ef6;    // For EF 6

Specifying the Template Folder

// Absolute path
Settings.TemplateFolder = @"c:\path_to_your_templates";

// Relative to the .tt file (recommended)
Settings.TemplateFolder = Path.Combine(Settings.Root, "Templates");

Settings.Root is the full directory path where your Database.tt file lives.

Template File Types

The template folder contains two types of files:

.txt files — namespace usings

One using namespace per line, without the using keyword or semicolons. Example contents of Usings.txt:

System
System.Collections.Generic
System.ComponentModel.DataAnnotations
System.ComponentModel.DataAnnotations.Schema

.mustache files — code templates

Mustache templates that transform data model objects into generated C# code.

Mustache tips:

  • Use {{#newline}} at line endings to control line breaks
  • Place {{#if}}/{{/if}} blocks at the start of a line to avoid extra whitespace
  • Use {{#each}}/{{/each}} to iterate over collections

Example — Poco.mustache snippet:

{{ClassComment}}
{{#if HasAttributes}}
{{Attributes}}
{{/if}}
{{ClassModifier}} class {{NameHumanCase}}{{BaseClasses}}{{#newline}}
{{{#newline}}
{{#each Columns}}
    {{#if HasAttributes}}
    {{Attributes}}
    {{/if}}
    {{PropertyModifier}} {{WrapIfNullable}} {{NameHumanCase}} { get; {{PrivateSetterForComputedColumns}}set; }{{PropertyInitialisers}}{{InlineComments}}{{#newline}}
{{/each}}
}{{#newline}}

Getting the Latest Template Files

The latest built-in template files are in the _File based templates/ directory in the repository. Copy these to your template folder as a starting point, then customize as needed.

Multi-Context Support

For multi-context generation with file-based templates, see Generating multiple database contexts in a single go.

You can also override the template folder per context:

UPDATE MultiContext.Context SET TemplatePath = 'C:\path\to\templates' WHERE [Name] = 'context_name'

Template Engine

File-based templates use Mustache# (a .NET implementation of Mustache). For syntax reference, see the Mustache documentation.

Clone this wiki locally