-
Notifications
You must be signed in to change notification settings - Fork 225
Custom File‐Based Templates
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.
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 6Also set the GeneratorType to match:
Settings.GeneratorType = GeneratorType.EfCore; // For EfCore 8/9/10
Settings.GeneratorType = GeneratorType.Ef6; // For EF 6// 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.
The template folder contains two types of files:
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 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}}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.
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'File-based templates use Mustache# (a .NET implementation of Mustache). For syntax reference, see the Mustache documentation.