Skip to content

Custom file based templates

Simon Hughes edited this page Jun 25, 2022 · 13 revisions

This is activated if

Settings.TemplateType = TemplateType.FileBased;

Using Settings.TemplateType = TemplateType.FileBased means that you want to use your own custom templates for file generation. Therefore you need to specify the folder where those templates exist.

Single context generation

If you are using the single context generation (Settings.GenerateSingleDbContext = true), you can do that via:

Settings.TemplateFolder = "c:\\path_to_your_templates"; // Specify your path here

If the path is relative to your project, you can use:

Settings.TemplateFolder = Path.Combine(Settings.Root, "Templates");

Settings.Root is set to the full path where your <database.tt> file exists.

Templates

The latest template files can be found here.

Multi-context generation

If you are using the multi-context generation (Settings.GenerateSingleDbContext = false), then please read this.

Required template files

The templates use a mixture of plain text files for a list of Usings to place at the top of the generated code, and a mustache template file. The {{Mustache}} template documentation is available at github.com/jehugaleahsa/mustache-sharp

Each template is passed in a data model to convert into code. This model is created by the CodeGenerator class which is then passed, along with the template text, to the mustache compiler to be transformed.

Thanks to the awesome work by Travis Parks and Keith Williams for the Mustache# for .NET Core library which is available at github.com/SunBrandingSolutions/mustache-sharp

Template types

These fall into two types:

  • txt files - These contain the usings required for the template. Place each using namespace on a separate line, no using or semi-colon ;. For example:
    System
    System.Data
    System.Linq
    
  • mustache files - These contain the mustache template text used to convert the passed in model into code.

Text files

Mustache files

DatabaseContextInterface.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class InterfaceModel
{
    public string interfaceModifier                                      { get; set; }
    public string DbContextInterfaceName                                 { get; set; }
    public string DbContextInterfaceBaseClasses                          { get; set; }
    public string DbContextName                                          { get; set; }
    public List<TableTemplateData> tables                                { get; set; }
    public List<string> AdditionalContextInterfaceItems                  { get; set; }
    public bool addSaveChanges                                           { get; set; }
    public List<StoredProcTemplateData> storedProcs                      { get; set; }
    public bool hasStoredProcs                                           { get; set; }
    public List<TableValuedFunctionsTemplateData> tableValuedFunctions   { get; set; }
    public List<ScalarValuedFunctionsTemplateData> scalarValuedFunctions { get; set; }
    public bool hasTableValuedFunctions                                  { get; set; }
    public bool hasScalarValuedFunctions                                 { get; set; }
}

DatabaseContext.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class ContextModel
{
    public string DbContextClassModifiers                                { get; set; }
    public string DbContextName                                          { get; set; }
    public string DbContextBaseClass                                     { get; set; }
    public bool AddParameterlessConstructorToDbContext                   { get; set; }
    public bool HasDefaultConstructorArgument                            { get; set; }
    public string DefaultConstructorArgument                             { get; set; }
    public string ConfigurationClassName                                 { get; set; }
    public string contextInterface                                       { get; set; }
    public string setInitializer                                         { get; set; }
    public bool DbContextClassIsPartial                                  { get; set; }
    public bool SqlCe                                                    { get; set; }
    public List<TableTemplateData> tables                                { get; set; }
    public bool hasTables                                                { get; set; }
    public List<string> indexes                                          { get; set; }
    public bool hasIndexes                                               { get; set; }
    public List<StoredProcTemplateData> storedProcs                      { get; set; }
    public bool hasStoredProcs                                           { get; set; }
    public List<string> tableValuedFunctionComplexTypes                  { get; set; }
    public bool hasTableValuedFunctionComplexTypes                       { get; set; }
    public List<string> AdditionalContextInterfaceItems                  { get; set; }
    public bool addSaveChanges                                           { get; set; }
    public List<TableValuedFunctionsTemplateData> tableValuedFunctions   { get; set; }
    public List<ScalarValuedFunctionsTemplateData> scalarValuedFunctions { get; set; }
    public List<RawSequence> Sequences                                   { get; set; }
    public bool hasSequences                                             { get; set; }
    public bool hasTableValuedFunctions                                  { get; set; }
    public bool hasScalarValuedFunctions                                 { get; set; }
    public string ConnectionString                                       { get; set; }
    public string ConnectionStringName                                   { get; set; }
    public string ConnectionStringActions                                { get; set; }
    public bool IncludeObjectContextConstructor                          { get; set; }
    public string QueryString                                            { get; set; }
    public string FromSql                                                { get; set; }
    public string ExecuteSqlCommand                                      { get; set; }
    public string StoredProcModelBuilderCommand                          { get; set; }
    public string StoredProcModelBuilderPostCommand                      { get; set; }
    public bool OnConfigurationUsesConfiguration                         { get; set; }
    public bool OnConfigurationUsesConnectionString                      { get; set; }
    public string DefaultSchema                                          { get; set; }
    public string UseDatabaseProvider                                    { get; set; }
    public string SqlParameter                                           { get; set; }
}

DatabaseContextFactory.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class FactoryModel
{
    public string classModifier { get; set; }
    public string contextName   { get; set; }
}

FakeDatabaseContext.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class FakeContextModel
{
    public string DbContextClassModifiers                                { get; set; }
    public string DbContextName                                          { get; set; }
    public string DbContextBaseClass                                     { get; set; }
    public string contextInterface                                       { get; set; }
    public bool DbContextClassIsPartial                                  { get; set; }
    public List<TableTemplateData> tables                                { get; set; }
    public List<StoredProcTemplateData> storedProcs                      { get; set; }
    public bool hasStoredProcs                                           { get; set; }
    public List<TableValuedFunctionsTemplateData> tableValuedFunctions   { get; set; }
    public List<ScalarValuedFunctionsTemplateData> scalarValuedFunctions { get; set; }
    public bool hasTableValuedFunctions                                  { get; set; }
    public bool hasScalarValuedFunctions                                 { get; set; }
}

FakeDbSet.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class FakeDbSetModel
{
    public string DbContextClassModifiers { get; set; }
    public bool DbContextClassIsPartial   { get; set; }
}

Poco.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class PocoModel
{
    public bool UseHasNoKey                                                   { get; set; }
    public bool HasNoPrimaryKey                                               { get; set; }
    public string Name                                                        { get; set; }
    public string NameHumanCaseWithSuffix                                     { get; set; }
    public string ClassModifier                                               { get; set; }
    public string ClassComment                                                { get; set; }
    public string ExtendedComments                                            { get; set; }
    public string ClassAttributes                                             { get; set; }
    public string BaseClasses                                                 { get; set; }
    public string InsideClassBody                                             { get; set; }
    public List<PocoColumnModel> Columns                                      { get; set; }
    public bool HasReverseNavigation                                          { get; set; }
    public List<PocoReverseNavigationPropertyModel> ReverseNavigationProperty { get; set; }
    public bool HasForeignKey                                                 { get; set; }
    public string ForeignKeyTitleComment                                      { get; set; }
    public List<PocoForeignKeyModel> ForeignKeys                              { get; set; }
    public bool CreateConstructor                                             { get; set; }
    public List<PocoColumnsWithDefaultsModel> ColumnsWithDefaults             { get; set; }
    public List<string> ReverseNavigationCtor                                 { get; set; }
    public bool EntityClassesArePartial                                       { get; set; }
    public bool HasHierarchyId                                                { get; set; }
}

public class PocoColumnModel
{
    public bool AddNewLineBefore                  { get; set; }
    public bool HasSummaryComments                { get; set; }
    public string SummaryComments                 { get; set; }
    public List<string> Attributes                { get; set; }
    public bool OverrideModifier                  { get; set; }
    public string WrapIfNullable                  { get; set; }
    public string NameHumanCase                   { get; set; }
    public string PrivateSetterForComputedColumns { get; set; }
    public string PropertyInitialisers            { get; set; }
    public string InlineComments                  { get; set; }
}

public class PocoReverseNavigationPropertyModel
{
    public bool ReverseNavHasComment                            { get; set; }
    public string ReverseNavComment                             { get; set; }
    public string[] AdditionalReverseNavigationsDataAnnotations { get; set; }
    public string[] AdditionalDataAnnotations                   { get; set; }
    public string Definition                                    { get; set; }
}

public class PocoForeignKeyModel
{
    public bool HasFkComment                             { get; set; }
    public string FkComment                              { get; set; }
    public string[] AdditionalForeignKeysDataAnnotations { get; set; }
    public string[] AdditionalDataAnnotations            { get; set; }
    public string Definition                             { get; set; }
}

public class PocoColumnsWithDefaultsModel
{
    public string NameHumanCase { get; set; }
    public string Default       { get; set; }
}

PocoConfiguration.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class PocoConfigurationModel
{
    public string Name                                                        { get; set; }
    public string ConfigurationClassName                                      { get; set; }
    public string NameHumanCaseWithSuffix                                     { get; set; }
    public string Schema                                                      { get; set; }
    public string PrimaryKeyNameHumanCase                                     { get; set; }
    public bool HasSchema                                                     { get; set; }
    public string ClassModifier                                               { get; set; }
    public string ClassComment                                                { get; set; }
    public List<string> Columns                                               { get; set; }
    public bool HasReverseNavigation                                          { get; set; }
    public List<PocoReverseNavigationPropertyModel> ReverseNavigationProperty { get; set; }
    public bool HasForeignKey                                                 { get; set; }
    public List<string> ForeignKeys                                           { get; set; }
    public List<string> MappingConfiguration                                  { get; set; }
    public List<string> Indexes                                               { get; set; }
    public bool HasIndexes                                                    { get; set; }
    public bool ConfigurationClassesArePartial                                { get; set; }
    public bool UseHasNoKey                                                   { get; set; }
    public string ToTableOrView                                               { get; set; }
    public bool UsesDictionary                                                { get; set; }
}

StoredProcReturnModels.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class StoredProcReturnModel
{
    public string ResultClassModifiers                                 { get; set; }
    public string WriteStoredProcReturnModelName                       { get; set; }
    public bool SingleModel                                            { get; set; }
    public List<string> SingleModelReturnColumns                       { get; set; }
    public List<MultipleModelReturnColumns> MultipleModelReturnColumns { get; set; }
}

Usings.mustache

This contains a mustache text used to convert the List<string> usings into code. There is no model class.

Enums.mustache

This contains a mustache text used to convert the model into code. The model is as follows:

public class Enumeration
{
    public readonly string EnumName;
    public readonly List<KeyValuePair<string, string>> Items;
}

Examples

Not all of the examples are listed here, just a few of the smallest ones to give you an idea of what they look like.

Enums.mustache

{{#each EnumAttributes}}
{{this}}{{#newline}}
{{/each}}
public enum {{EnumName}}{{#newline}}
{{{#newline}}
{{#each Items}}
{{#each Attributes}}
    {{this}}{{#newline}}
{{/each}}
    {{Key}} = {{Value}},{{#newline}}
{{/each}}
}{{#newline}}

StoredProcReturnModels.mustache

{{ResultClassModifiers}} class {{WriteStoredProcReturnModelName}}{{#newline}}
{{{#newline}}
{{#if SingleModel}}
{{#each SingleModelReturnColumns}}
    {{this}}{{#newline}}
{{/each}}
{{#else}}
{{#each MultipleModelReturnColumns}}
    public class ResultSetModel{{Model}}{{#newline}}
    {{{#newline}}
{{#each ReturnColumns}}
        {{this}}{{#newline}}
{{/each}}
    }{{#newline}}
    public List<ResultSetModel{{Model}}> ResultSet{{Model}};{{#newline}}
{{/each}}
{{/if}}
}{{#newline}}

Usings.mustache

{{#each this}}
using {{this}};{{#newline}}
{{/each}}

Mustache tips

  • Don't forget to use {{#newline}} at the end of lines.
  • Put {{#if}}, {{/if}}, etc at the start of a line, otherwise you end up with extra spaces in the generated code.

Clone this wiki locally