-
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.
- Core / Required Settings
- Output File Organization
- Elements to Generate
- Cross-Namespace References
-
DbContext Settings
- Settings.DbContextBaseClass
- Settings.DbContextInterfaceBaseClasses
- Settings.OnConfiguration
- Settings.AddParameterlessConstructorToDbContext
- Settings.AddIDbContextFactory
- Settings.AddUnitTestingDbContext
- 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
- Multi-Context Generation
- HiLo Sequences
- Enumerations
- Foreign Key Naming Strategy
- 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)";Generated files are now always written the same way, so this setting no longer exists. Delete the line from
your .tt when upgrading - see Upgrading from v3 to v4.
Type: string
Default: "MyDbContext"
The class name for the generated DbContext.
Settings.DbContextName = "NorthwindDbContext";Type: string
Default: typeof(Settings).Namespace
The namespace for all generated files. Defaults to the namespace of the project.
Settings.Namespace = "MyCompany.MyProject.Data";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 fileType: string
Default: ""
Sub-folder for the generated DbContext file.
Settings.ContextFolder = @"Data";Type: string
Default: ""
Sub-folder for the generated interface file.
Settings.InterfaceFolder = @"Data\Interface";Type: string
Default: ""
Sub-folder for the generated POCO entity classes.
Settings.PocoFolder = @"Data\Entities";Type: string
Default: ""
Sub-folder for the generated Fluent API configuration mapping classes.
Settings.PocoConfigurationFolder = @"Data\Configuration";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.ConfigurationType: 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";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 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)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: true
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.
Settings.PrependSchemaName = true;
// dbo.Orders → Orders
// billing.Orders → Billing_Orders
Settings.PrependSchemaName = false;
// dbo.Orders → Orders
// billing.Orders → Orders (potential name conflict!)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 directives.
Type: bool
Default: false
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("EntityFramework 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: 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: false
Disables generation of spatial types (geography, geometry). Required for OData compatibility.
Settings.DisableGeographyTypes = true; // Disable (e.g., for OData)
Settings.DisableGeographyTypes = false; // Enable (default)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: 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: ForeignKeyNamingStrategy enum
Default: ForeignKeyNamingStrategy.Current
Controls how foreign key navigation property names are generated.
Settings.ForeignKeyNamingStrategy = ForeignKeyNamingStrategy.Current; // Current behavior
Settings.ForeignKeyNamingStrategy = ForeignKeyNamingStrategy.Legacy; // Previous behavior (use if upgrading)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