-
Notifications
You must be signed in to change notification settings - Fork 226
Settings Reference
This page documents all settings available in Database.tt. Settings are applied before the generator runs; save the file to trigger regeneration.
All settings are members of the static Settings class. Unless noted otherwise, they apply to both EF 6 and EF Core.
Some settings now have a page of their own, with worked before-and-after examples of the generated code. Where one exists it is linked from the entry here, and it is the fuller answer. So far: ElementsToGenerate | OnConfiguration | PrependSchemaNameForTable | UpdateColumn | UsePrivateSetterForComputedColumns
"Default" below means the value the shipped Database.tt assigns, which is what you actually get in a new
file. A few of those differ from the Settings class field initialiser; the .tt line is the one that runs
last, so it is the one that counts.
-
Core / Required Settings
- Settings.DatabaseType
- Settings.TemplateType
- Settings.GeneratorType
- Settings.ConnectionString
- Settings.ConnectionStringName
- Settings.ConnectionStringActions
- Settings.DbContextName
- Settings.DbContextInterfaceName
- Settings.Namespace
- Settings.UseFileScopedNamespaces
- Settings.TemplateFolder
- Settings.GenerateSeparateFiles
- Output File Organization
- Elements to Generate
- Cross-Namespace References
-
DbContext Settings
- Settings.DbContextBaseClass
- Settings.DbContextInterfaceBaseClasses
- Settings.OnConfiguration
- Settings.AddParameterlessConstructorToDbContext
- Settings.AddIDbContextFactory
- Settings.AddUnitTestingDbContext
- Settings.FakeDbContextInDebugOnlyMode
- Settings.UseInheritedBaseInterfaceFunctions
- Settings.AdditionalContextInterfaceItems
- Settings.DbContextClassModifiers
- Settings.DbContextInterfaceModifiers
- Settings.EntityClassesModifiers
- Settings.ConfigurationClassesModifiers
- Settings.ResultClassModifiers
-
POCO Class Settings
- Settings.UsePascalCase
- Settings.UsePascalCaseForEnumMembers
- Settings.UseDataAnnotations
- Settings.UsePropertyInitialisers
- Settings.UseLazyLoading
- Settings.IncludeComments
- Settings.IncludeExtendedPropertyComments
- Settings.CollectionInterfaceType
- Settings.CollectionType
- Settings.NullableShortHand
- Settings.UsePrivateSetterForComputedColumns
- Settings.IncludeFieldNameConstants
- Settings.IncludeColumnsWithDefaults
- Settings.AllowNullStrings
- Settings.NullableReverseNavigationProperties
- Settings.OrderProperties
- Settings.TableSuffix
- Settings.TrimCharFields
- Schema Settings
- Configuration Class Settings
- Stored Procedure Settings
- Code Formatting / Suppression
- Additional Content
- Performance
- Geography / Spatial Types
- SQL Server-Specific
- Removed in v4
- Multi-Context Generation
- HiLo Sequences
- Enumerations
- Mapping Tables (EF 6 only)
Type: DatabaseType enum
Default: DatabaseType.SqlServer
Specifies the database provider used to read the schema. See Common Settings Types Explained for all values.
Settings.DatabaseType = DatabaseType.SqlServer; // SQL Server
Settings.DatabaseType = DatabaseType.PostgreSQL; // PostgreSQL
Settings.DatabaseType = DatabaseType.SQLite; // SQLite
Settings.DatabaseType = DatabaseType.MySql; // MySQL and MariaDB
Settings.DatabaseType = DatabaseType.Oracle; // OracleType: TemplateType enum
Default: TemplateType.EfCore10
Selects the code generation template. Must match the EF version you are targeting.
Settings.TemplateType = TemplateType.EfCore10; // EF Core 10 (latest)
Settings.TemplateType = TemplateType.EfCore9; // EF Core 9
Settings.TemplateType = TemplateType.EfCore8; // EF Core 8
Settings.TemplateType = TemplateType.Ef6; // Entity Framework 6
Settings.TemplateType = TemplateType.FileBasedCore10; // Custom Mustache templates, EF Core 10Type: GeneratorType enum
Default: GeneratorType.EfCore
Selects the generator implementation. Must be paired correctly with TemplateType.
Settings.GeneratorType = GeneratorType.EfCore; // Use with EfCore8/9/10 templates
Settings.GeneratorType = GeneratorType.Ef6; // Use with Ef6 template
Settings.GeneratorType = GeneratorType.Custom; // Edit GeneratorCustom classType: string
Default: ""
Required: Yes
The connection string used by the generator to read your database schema. This is also placed into the generated DbContext constructor when OnConfiguration = ConnectionString.
Settings.ConnectionString = "Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True;Encrypt=false;TrustServerCertificate=true";Using an environment variable (keeps credentials out of source control):
Settings.ConnectionString = Environment.GetEnvironmentVariable("MY_DB_CONN", EnvironmentVariableTarget.User);Type: string
Default: "MyDbContext"
The connection string key as it appears in appsettings.json / app.config. Used in the generated constructor. Not used by the generator itself.
Settings.ConnectionStringName = "MyDbContext";Type: string
Default: ""
EF Core only
Additional method chain appended to the database provider setup in OnConfiguring. Use this to add retry logic, timeouts, etc.
Settings.ConnectionStringActions = ".EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null)";Type: string
Default: "MyDbContext"
The class name for the generated DbContext.
Settings.DbContextName = "NorthwindDbContext";Type: string
Default: "I" + DbContextName
The name of the generated context interface. Commented out in Database.tt; uncomment to override. Set it to
an empty string to generate a DbContext that implements no interface.
Settings.DbContextInterfaceName = "INorthwind";
Settings.DbContextInterfaceName = ""; // No interfaceType: string
Default: DefaultNamespace
The namespace for all generated files. DefaultNamespace is supplied by the T4 host and resolves to your
project's root namespace. Use double quotes to override it.
Settings.Namespace = "MyCompany.MyProject.Data";Type: bool
Default: false
When true, emits C# 10 file-scoped namespaces (namespace X;) instead of block-scoped (namespace X { }).
Has no effect when Settings.UseNamespace = false. See File-Scoped Namespaces.
Type: string
Default: Path.Combine(Settings.Root, "Templates")
Only used when Settings.TemplateType is one of the FileBased* values. The folder must contain the
.mustache and *Usings.txt files directly. Settings.Root is the folder holding your .tt file. See
Custom File-Based Templates.
Type: bool
Default: false
When true, each POCO class, configuration mapping, etc. is generated in its own file. When false, all output is in a single Database.cs file.
Settings.GenerateSeparateFiles = true; // Separate files (recommended for larger projects)
Settings.GenerateSeparateFiles = false; // Single fileDatabase.tt assigns the four folder settings inside if (Settings.GenerateSeparateFiles), so they only
take effect when separate files are being generated. With a single output file there is nothing to put in a
sub-folder and the values are never read.
if (Settings.GenerateSeparateFiles)
{
Settings.ContextFolder = @"";
Settings.InterfaceFolder = @"Interface";
Settings.PocoFolder = @"Entities";
Settings.PocoConfigurationFolder = @"Configuration";
Settings.UseFolderNameInNamespace = false;
}Type: string
Default: @"" (alongside the .tt file)
Sub-folder for the generated DbContext file.
Settings.ContextFolder = @"Data";Type: string
Default: @"Interface"
Sub-folder for the generated interface file.
Settings.InterfaceFolder = @"Data\Interface";Type: string
Default: @"Entities"
Sub-folder for the generated POCO entity classes.
Settings.PocoFolder = @"Data\Entities";Type: string
Default: @"Configuration"
Sub-folder for the generated Fluent API configuration mapping classes.
Settings.PocoConfigurationFolder = @"Data\Configuration";Type: string
Default: ""
Sub-folder for auto-generated owned entity classes. Falls back to Settings.PocoFolder when empty. See
Owned Entities.
Settings.OwnedEntityFolder = @"Data\Owned";Type: bool
Default: false
When true, the sub-folder name is appended to the namespace of each generated file.
Settings.UseFolderNameInNamespace = true;
// PocoFolder = "Entities" => namespace MyProject.Entities
// PocoConfigurationFolder = "Configuration" => namespace MyProject.ConfigurationFull page: Settings.ElementsToGenerate
Type: Elements flags enum
Default: Elements.Poco | Elements.Context | Elements.Interface | Elements.PocoConfiguration | Elements.Enum
Controls which code artifacts are generated. Can be combined with |.
// Generate everything (default)
Settings.ElementsToGenerate = Elements.Poco | Elements.Context | Elements.Interface | Elements.PocoConfiguration | Elements.Enum;
// Generate only entity classes (for a dedicated Entities project)
Settings.ElementsToGenerate = Elements.Poco;
// Generate only context and interface (for a dedicated Data project)
Settings.ElementsToGenerate = Elements.Context | Elements.Interface;
// Generate only configuration mappings
Settings.ElementsToGenerate = Elements.PocoConfiguration;Use these when splitting generated elements across multiple assemblies or projects. They add using statements; they do not move the files.
Settings.ContextNamespace = "MyProject.Data";
Settings.InterfaceNamespace = "MyProject.Data";
Settings.PocoNamespace = "MyProject.Data.Entities";
Settings.PocoConfigurationNamespace = "MyProject.Data.Configuration";Type: string
Default: "DbContext"
The base class for the generated DbContext.
Settings.DbContextBaseClass = "DbContext";
// ASP.NET Core Identity
Settings.DbContextBaseClass = "IdentityDbContext<ApplicationUser>";
// Custom base class
Settings.DbContextBaseClass = "MyBaseDbContext";Type: string
Default: "IDisposable"
Base interfaces for the generated IDbContext interface.
Settings.DbContextInterfaceBaseClasses = "IDisposable";
Settings.DbContextInterfaceBaseClasses = "IDisposable, IMyBaseInterface";Full page: Settings.OnConfiguration
Type: OnConfiguration enum
Default: OnConfiguration.ConnectionString
EF Core only
Controls the code generated inside DbContext.OnConfiguring(). See Settings.OnConfiguration for full details.
Settings.OnConfiguration = OnConfiguration.ConnectionString; // Embed connection string
Settings.OnConfiguration = OnConfiguration.Configuration; // Use IConfiguration DI
Settings.OnConfiguration = OnConfiguration.Omit; // Remove OnConfiguring entirelyType: bool
Default: true
EF 6 only
When true, adds a parameterless constructor to the DbContext that passes the connection string name.
Type: bool
Default: true
Adds a default IDbContextFactory<DbContextName> implementation for easy dependency injection.
Type: bool
Default: true
Adds a FakeDbContext and FakeDbSet for unit testing. See FakeDbContext.
Settings.AddUnitTestingDbContext = true;Type: bool
Default: false
When true, the generated Fake* classes are wrapped in #if DEBUG / #endif so they are excluded from
Release builds. Only meaningful when Settings.AddUnitTestingDbContext = true.
Type: bool
Default: false
When true, the IDbContext interface functions come from DbContextInterfaceBaseClasses (not generated). When false, they are generated explicitly.
Type: List<string>
Default: empty
Extra method signatures to add to the generated IDbContext interface.
Settings.AdditionalContextInterfaceItems = new List<string>
{
"void SetAutoDetectChangesEnabled(bool flag);",
"int ExecuteSqlCommand(string sql, params object[] parameters);"
};Type: string
Default: "public"
Access modifiers for generated classes. Set to "public partial" to enable partial classes.
Settings.DbContextClassModifiers = "public partial"; // Enables OnModelCreatingPartial
Settings.EntityClassesModifiers = "public partial";
Settings.ConfigurationClassesModifiers = "public partial";Type: bool
Default: true
Renames generated C# class and property names to PascalCase. When false, names are used as-is from the database.
Settings.UsePascalCase = true; // "order_details" → "OrderDetails"
Settings.UsePascalCase = false; // Names left unchangedType: bool
Default: true
Renames generated enum member names to PascalCase.
Type: bool
Default: false
Adds Data Annotation attributes ([Key], [Required], [MaxLength], [StringLength], [Display], etc.) to generated POCO classes.
Settings.UseDataAnnotations = true;Automatically adds:
-
[Key, Column(Order = n)]for primary key columns -
[Required]or[Required(AllowEmptyStrings = true)]for non-nullable columns -
[MaxLength(n)]and[StringLength(n)]for string columns with a max length -
[MaxLength]for max-length string columns -
[Timestamp, ConcurrencyCheck]for row version columns -
[Display(Name = "...")]for all columns -
[Column(TypeName = "vector(n)")]for SQL Server 2025 vector columns
Type: bool
Default: false
When true, removes the POCO constructor and uses C# 6 property initialisers to set default values instead.
Settings.UsePropertyInitialisers = false; // Use constructor to set defaults
Settings.UsePropertyInitialisers = true; // Use property initialisers: public string Name { get; set; } = "default";Type: bool
Default: false
Marks all navigation properties as virtual to support EF lazy loading. See Lazy Loading for full setup instructions.
Settings.UseLazyLoading = false; // Recommended for web APIs
Settings.UseLazyLoading = true; // Enable lazy loading (requires additional setup for EF Core)Type: CommentsStyle enum
Default: CommentsStyle.AtEndOfField
Controls whether non-PascalCase names, PK/FK info, and lengths are added as comments.
Settings.IncludeComments = CommentsStyle.None; // No comments
Settings.IncludeComments = CommentsStyle.AtEndOfField; // // comment at end of line
Settings.IncludeComments = CommentsStyle.InSummaryBlock; // /// <summary> blocksType: CommentsStyle enum
Default: CommentsStyle.InSummaryBlock
Controls whether SQL Server extended property values are added as comments to POCO properties.
Settings.IncludeExtendedPropertyComments = CommentsStyle.InSummaryBlock;Type: string
Default: "ICollection"
The interface type used to declare navigation collection properties.
Settings.CollectionInterfaceType = "ICollection";
Settings.CollectionInterfaceType = "IList";
Settings.CollectionInterfaceType = "System.Collections.Generic.List";Type: string
Default: "List"
The concrete type used to instantiate navigation collections.
Settings.CollectionType = "List";
Settings.CollectionType = "ObservableCollection"; // Add "System.Collections.ObjectModel" to AdditionalNamespaces
Settings.CollectionType = "HashSet";Type: bool
Default: true
Controls nullable type syntax.
Settings.NullableShortHand = true; // int? (shorthand)
Settings.NullableShortHand = false; // Nullable<int> (longhand)Full page: Settings.UsePrivateSetterForComputedColumns
Type: bool
Default: true
When true, computed columns use private set; instead of set;.
Settings.UsePrivateSetterForComputedColumns = true;
// Generates: public string FullName { get; private set; }Type: bool
Default: false
Adds public const string {Name}Field = "{Name}"; constants to each POCO class, avoiding magic strings.
Settings.IncludeFieldNameConstants = true;
// Generates: public const string FirstNameField = "FirstName";Type: bool
Default: true
When true, sets property default values in the constructor to match database column defaults.
Type: bool
Default: false
When true, string properties can be nullable (string?) and #nullable enable is added to the top of each file.
Settings.AllowNullStrings = true; // string? nullable strings
Settings.AllowNullStrings = false; // string non-nullable strings (default)Type: bool
Default: false
When true, reverse navigation properties for one-to-one relationships are nullable (MyEntity?), reflecting that the child may not exist.
Settings.NullableReverseNavigationProperties = true;
// Generates: public virtual ChildEntity? Child { get; set; }Type: OrderProperties enum
Default: OrderProperties.Ordinal
Controls the order properties appear within generated POCO classes.
Settings.OrderProperties = OrderProperties.Ordinal; // Database column order
Settings.OrderProperties = OrderProperties.Alphabetical; // A-Z orderType: string
Default: null
Appends a suffix to all generated entity class names.
Settings.TableSuffix = "Dto"; // Order → OrderDto
Settings.TableSuffix = "Entity"; // Order → OrderEntity
Settings.TableSuffix = null; // No suffix (default)Type: bool
Default: false
EF Core only
When true, adds .TrimEnd() to char fields when they are read from the database.
Settings.TrimCharFields = true;Type: bool
Default: true
Controls whether the schema name is prepended to generated class names for non-default schemas. The schema is prepended exactly as the database spells it - it is not PascalCased - while the table name is singularised and PascalCased as usual.
Settings.PrependSchemaName = true;
// dbo.Orders → Order
// billing.Orders → billing_Order
Settings.PrependSchemaName = false;
// dbo.Orders → Order
// billing.Orders → Order (potential name conflict!)Full page: Settings.PrependSchemaNameForTable
Type: Func<Table, bool>
Default: returns true for every table
Not in Database.tt - you have to add it yourself
Decides per table whether the schema is prepended, instead of PrependSchemaName's all-or-nothing. Only
consulted for tables outside the default schema.
Settings.PrependSchemaNameForTable = table =>
!table.Schema.DbName.Equals("sales", StringComparison.OrdinalIgnoreCase);Settings.PrependSchemaNameForStoredProcedure is the same thing for stored procedures.
Type: string
Default: null
The schema that is treated as the default and therefore never prepended. It is set for you by the database reader, so you rarely assign it yourself:
| Database | Default schema |
|---|---|
| SQL Server |
SCHEMA_NAME(), the connected login's default schema. Falls back to dbo
|
| PostgreSQL | public |
| MySQL / MariaDB |
DATABASE(), i.e. whatever Database= names |
| Oracle |
SYS_CONTEXT('USERENV','CURRENT_SCHEMA'), i.e. the connected user |
| SQLite | main |
Note the SQL Server row: if your login's default schema is not dbo, then dbo is prepended and your
dbo tables generate as dbo_Order. It is useful to read Settings.DefaultSchema inside callbacks, which
is why Database.tt uses it throughout its EnumDefinition and AddRelationship examples.
Type: string
Default: "Configuration"
The suffix appended to each POCO class name to create the Fluent API configuration class name.
Settings.ConfigurationClassName = "Configuration"; // OrderConfiguration
Settings.ConfigurationClassName = "Mapping"; // OrderMapping
Settings.ConfigurationClassName = "Map"; // OrderMapType: bool
Default: false
Controls whether stored procedure result set collections are generated as fields or properties.
Settings.UsePropertiesForStoredProcResultSets = false; // public List<ResultSet1> ResultSet1;
Settings.UsePropertiesForStoredProcResultSets = true; // public List<ResultSet1> ResultSet1 { get; set; }Type: bool
Default: true
Some stored procedures are reported as having multiple result sets when they actually return one. When true, identical result sets are merged into one.
Type: Dictionary<string, string>
Override the generated return type for stored procedures that return entities.
// "SalesByYear" stored proc → return SummaryOfSalesByYear entity instead of a generated model
Settings.StoredProcedureReturnTypes.Add("SalesByYear", "SummaryOfSalesByYear");Type: bool
Default: true
When false, suppresses #region / #endregion blocks.
Type: bool
Default: true
When false, suppresses the namespace declaration.
Type: bool
Default: false
When true, adds #pragma warning disable 1591 (ignore "Missing XML Comment") to the top of each generated
file.
Type: bool
Default: true
When true, adds ReSharper // ReSharper disable comments to suppress inspection warnings.
Type: bool
Default: false
When true, adds the generator licence info as a comment at the top of each file.
Type: bool
Default: false
When true, adds a comment describing the connection settings used to generate the file.
Type: bool
Default: false
When true, adds [GeneratedCode("EF.Reverse.POCO.Generator", "<version>")] to generated classes.
Type: bool
Default: false
When true, includes the generator version number in the generated code. Requires ShowLicenseInfo = true.
Type: bool
Default: false
EF Core only
When true, emits .HasDefaultValueSql("...") in the entity configuration for columns with a SQL default value. This makes defaults queryable via EF model reflection.
Settings.GenerateHasDefaultValueSql = true;
// Generates: builder.Property(x => x.CreatedAt).HasDefaultValueSql("getutcdate()");Type: List<string>
Extra using namespaces added to all generated files.
Settings.AdditionalNamespaces = new List<string>
{
"Microsoft.AspNetCore.Identity.EntityFrameworkCore",
"System.ComponentModel.DataAnnotations"
};Type: List<string>
Lines added verbatim near the top of each generated file, below the auto-generated comment.
Settings.AdditionalFileHeaderText = new List<string>
{
"#nullable enable",
"// Generated by MyTeam generator"
};Type: List<string>
Lines added verbatim at the bottom of each generated file, above the closing // </auto-generated> comment.
Type: GenerationLanguage enum / string
Default: GenerationLanguage.CSharp / ".cs"
GenerationLanguage.Javascript swaps in a JavaScript type map and is SQL Server only; every other database
falls back to C#. It changes the property types only - the templates themselves are unchanged - so treat it as
experimental. Set FileExtension to match if you change it.
Type: string[]
Data annotation attribute names (without brackets) applied to all reverse navigation properties. Useful for JSON serialization exclusion.
Settings.AdditionalReverseNavigationsDataAnnotations = new string[]
{
"JsonIgnore" // Also add "Newtonsoft.Json" to AdditionalNamespaces
};Type: string[]
Data annotation attribute names applied to all foreign key properties.
Settings.AdditionalForeignKeysDataAnnotations = new string[]
{
"JsonIgnore"
};Type: int
Default: 600
SQL command timeout in seconds. Set to 0 to wait indefinitely. Some databases can be slow when retrieving schema information.
Settings.CommandTimeout = 600; // 10 minutes (default)
Settings.CommandTimeout = 0; // No timeoutType: bool
Default: true
Disables generation of spatial types (geography, geometry). The shipped Database.tt sets this to
true, so spatial types are off until you turn them on. Leaving it true is also what OData needs, since
OData does not support entities with geometry/geography types.
Settings.DisableGeographyTypes = true; // Disable - the shipped default
Settings.DisableGeographyTypes = false; // Enable spatial typesWhen true, a stored procedure with a spatial parameter or a spatial column in its return model is not
generated at all.
See Spatial Types for setup.
Type: bool
Default: false
When true, adds OPTION (QUERYTRACEON 9481) to schema queries. Use this if SQL Server 2014 appears to freeze or take a very long time when the .tt file is saved. Requires elevated database privileges.
Removed. Settings.DatabaseReaderPlugin and DatabaseType.Plugin let you supply your own schema reader as
a .NET Framework assembly loaded into the T4 host. Database reading now happens in the separate efrpg tool,
so there is nothing to load it into.
If you were using one, please open an issue describing what your plugin did. If it read a database EFRPG does not support, that is a case for adding the dialect to the tool.
Removed. See above.
Type: bool
Default: true
When false, enables multi-context generation mode. See Generating multiple database contexts in a single go.
Type: string
Default: ""
Connection string to the database containing the multi-context settings tables. Leave empty to use the same database as ConnectionString.
Type: char
Default: '~'
The character used to split multiple attribute values stored in one MultiContext.* settings column, for
example '[Foo]~[Bar]'.
Type: string
Default: ""
"c:\\Path\\YourMultiDbSettingsReader.dll,Full.Name.Of.Class.Including.Namespace". Supplies your own reader
for the multi-context settings instead of the built-in MultiContext.* tables. Setting it also stops the
efrpg tool being asked to read those tables.
Type: List<HiLoSequence>
Configures HiLo sequence-based identity generation for specific tables/columns instead of the default identity column.
Settings.HiLoSequences = new List<HiLoSequence>
{
new HiLoSequence
{
Schema = "dbo",
Table = "Employees", // Use * to match all tables in the schema
SequenceName = "EmployeeSequence",
SequenceSchema = "dbo"
}
};Type: List<EnumerationSettings>
Defines database tables that should be read and converted into C# enumerations. See Enum Generation from Table Data for full details.
Type: bool
Default: false
EF 6 only. When true, many-to-many mapping tables are not generated as POCOs; instead, EF generates them implicitly via HasMany(...).WithMany(...). Must be false for EF Core.
Settings.UseMappingTables = true; // EF 6 only
Settings.UseMappingTables = false; // Required for EF Core- Home
- Compared with the Microsoft scaffolder
- Connection strings
- JetBrains Rider
- Upgrading from v3 to v4
- Saving .tt does nothing
- Settings A-Z - every setting, with a page each
- Common Settings Types Explained
- Settings Callbacks
- Settings runtime values and helpers
- Filtering
- Full Control Over the Generated Code
- Enum Generation from Table Data
- Owned Entities
- JSON column support
- Global Query Filters
- Extended Property Names Feature
- Partial Properties
- File-Scoped Namespaces
- Data Annotations
- Spatial Types
- HierarchyId
- RowVersion and TimeStamp columns
- Lazy Loading
- Stored proc result sets