Skip to content

Adds support for Using EntityTypeConfiguration files. #2582

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
270 changes: 270 additions & 0 deletions samples/CodeTemplates/EFCore/EntityTypeConfiguration.t4
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
<#@ template hostSpecific="true" debug="false" #>
<#@ assembly name="Microsoft.EntityFrameworkCore" #>
<#@ assembly name="Microsoft.EntityFrameworkCore.Design" #>
<#@ assembly name="Microsoft.EntityFrameworkCore.Relational" #>
<#@ assembly name="Microsoft.Extensions.DependencyInjection.Abstractions" #>
<#@ parameter name="EntityType" type="Microsoft.EntityFrameworkCore.Metadata.IEntityType" #>
<#@ parameter name="Options" type="Microsoft.EntityFrameworkCore.Scaffolding.ModelCodeGenerationOptions" #>
<#@ parameter name="NamespaceHint" type="System.String" #>
<#@ parameter name="ProjectDefaultNamespace" type="System.String" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="Microsoft.EntityFrameworkCore" #>
<#@ import namespace="Microsoft.EntityFrameworkCore.Design" #>
<#@ import namespace="Microsoft.EntityFrameworkCore.Infrastructure" #>
<#@ import namespace="Microsoft.EntityFrameworkCore.Scaffolding" #>
<#@ import namespace="Microsoft.Extensions.DependencyInjection" #>
<#@ import namespace="Microsoft.EntityFrameworkCore.Metadata.Builders" #>
<#
if (!ProductInfo.GetVersion().StartsWith("7.0"))
{
Warning("Your templates were created using an older version of Entity Framework. Additional features and bug fixes may be available. See https://aka.ms/efcore-docs-updating-templates for more information.");
}

var services = (IServiceProvider)Host;
var providerCode = services.GetRequiredService<IProviderConfigurationCodeGenerator>();
var annotationCodeGenerator = services.GetRequiredService<IAnnotationCodeGenerator>();
var code = services.GetRequiredService<ICSharpHelper>();

var usings = new List<string>
{
"System",
"System.Collections.Generic",
"Microsoft.EntityFrameworkCore"
};

if (NamespaceHint != Options.ModelNamespace
&& !string.IsNullOrEmpty(Options.ModelNamespace))
{
usings.Add(Options.ModelNamespace);
}
usings.Add(typeof(EntityTypeBuilder<>).Namespace);

if (!string.IsNullOrEmpty(NamespaceHint))
{
#>
namespace <#= NamespaceHint #>.Configurations;

<#
}
#>
public partial class <#= EntityType.Name #>Configuration : IEntityTypeConfiguration<<#= EntityType.Name #>>
{
public void Configure(EntityTypeBuilder<<#= EntityType.Name #>> entity)
{
<#
var anyConfiguration = false;

StringBuilder mainEnvironment;
if (EntityType?.Name!=null)
{
// Save all previously generated code, and start generating into a new temporary environment
mainEnvironment = GenerationEnvironment;
GenerationEnvironment = new StringBuilder();

var anyEntityTypeConfiguration = false;
var key = EntityType.FindPrimaryKey();
if (key != null)
{
var keyFluentApiCalls = key.GetFluentApiCalls(annotationCodeGenerator);
if (keyFluentApiCalls != null
|| (!key.IsHandledByConvention() && !Options.UseDataAnnotations))
{
if (keyFluentApiCalls != null)
{
usings.AddRange(keyFluentApiCalls.GetRequiredUsings());
}
#>
entity.HasKey(<#= code.Lambda(key.Properties, "e") #>)<#= code.Fragment(keyFluentApiCalls, indent: 3) #>;
<#
anyEntityTypeConfiguration = true;
}
}

var entityTypeFluentApiCalls = EntityType.GetFluentApiCalls(annotationCodeGenerator)
?.FilterChain(c => !(Options.UseDataAnnotations && c.IsHandledByDataAnnotations));
if (entityTypeFluentApiCalls != null)
{
usings.AddRange(entityTypeFluentApiCalls.GetRequiredUsings());

if (anyEntityTypeConfiguration)
{
WriteLine("");
}
#>
entity<#= code.Fragment(entityTypeFluentApiCalls, indent: 3) #>;
<#
anyEntityTypeConfiguration = true;
}

foreach (var index in EntityType.GetIndexes()
.Where(i => !(Options.UseDataAnnotations && i.IsHandledByDataAnnotations(annotationCodeGenerator))))
{
if (anyEntityTypeConfiguration)
{
WriteLine("");
}

var indexFluentApiCalls = index.GetFluentApiCalls(annotationCodeGenerator);
if (indexFluentApiCalls != null)
{
usings.AddRange(indexFluentApiCalls.GetRequiredUsings());
}
#>
entity.HasIndex(<#= code.Lambda(index.Properties, "e") #>, <#= code.Literal(index.GetDatabaseName()) #>)<#= code.Fragment(indexFluentApiCalls, indent: 3) #>;
<#
anyEntityTypeConfiguration = true;
}

var firstProperty = true;
foreach (var property in EntityType.GetProperties())
{
var propertyFluentApiCalls = property.GetFluentApiCalls(annotationCodeGenerator)
?.FilterChain(c => !(Options.UseDataAnnotations && c.IsHandledByDataAnnotations)
&& !(c.Method == "IsRequired" && Options.UseNullableReferenceTypes && !property.ClrType.IsValueType));
if (propertyFluentApiCalls == null)
{
continue;
}

usings.AddRange(propertyFluentApiCalls.GetRequiredUsings());

if (anyEntityTypeConfiguration && firstProperty)
{
WriteLine("");
}
#>
entity.Property(e => e.<#= property.Name #>)<#= code.Fragment(propertyFluentApiCalls, indent: 3) #>;
<#
anyEntityTypeConfiguration = true;
firstProperty = false;
}

foreach (var foreignKey in EntityType.GetForeignKeys())
{
var foreignKeyFluentApiCalls = foreignKey.GetFluentApiCalls(annotationCodeGenerator)
?.FilterChain(c => !(Options.UseDataAnnotations && c.IsHandledByDataAnnotations));
if (foreignKeyFluentApiCalls == null)
{
continue;
}

usings.AddRange(foreignKeyFluentApiCalls.GetRequiredUsings());

if (anyEntityTypeConfiguration)
{
WriteLine("");
}
if (foreignKey.DependentToPrincipal?.Name != null && foreignKey.PrincipalToDependent?.Name != null)
{
#>
entity.HasOne(d => d.<#= foreignKey.DependentToPrincipal.Name #>).<#= foreignKey.IsUnique ? "WithOne" : "WithMany" #>(p => p.<#= foreignKey.PrincipalToDependent.Name #>)<#= code.Fragment(foreignKeyFluentApiCalls, indent: 3) #>;
<#
}
anyEntityTypeConfiguration = true;
}

foreach (var skipNavigation in EntityType.GetSkipNavigations().Where(n => n.IsLeftNavigation()))
{
if (anyEntityTypeConfiguration)
{
WriteLine("");
}

var left = skipNavigation.ForeignKey;
var leftFluentApiCalls = left.GetFluentApiCalls(annotationCodeGenerator, useStrings: true);
var right = skipNavigation.Inverse.ForeignKey;
var rightFluentApiCalls = right.GetFluentApiCalls(annotationCodeGenerator, useStrings: true);
var joinEntityType = skipNavigation.JoinEntityType;

if (leftFluentApiCalls != null)
{
usings.AddRange(leftFluentApiCalls.GetRequiredUsings());
}

if (rightFluentApiCalls != null)
{
usings.AddRange(rightFluentApiCalls.GetRequiredUsings());
}
#>
entity.HasMany(d => d.<#= skipNavigation.Name #>).WithMany(p => p.<#= skipNavigation.Inverse.Name #>)
.UsingEntity<Dictionary<string, object>>(
<#= code.Literal(joinEntityType.Name) #>,
r => r.HasOne<<#= right.PrincipalEntityType.Name #>>().WithMany()<#= code.Fragment(rightFluentApiCalls, indent: 6) #>,
l => l.HasOne<<#= left.PrincipalEntityType.Name #>>().WithMany()<#= code.Fragment(leftFluentApiCalls, indent: 6) #>,
j =>
{
<#
var joinKey = joinEntityType.FindPrimaryKey();
var joinKeyFluentApiCalls = joinKey.GetFluentApiCalls(annotationCodeGenerator);

if (joinKeyFluentApiCalls != null)
{
usings.AddRange(joinKeyFluentApiCalls.GetRequiredUsings());
}
#>
j.HasKey(<#= code.Arguments(joinKey.Properties.Select(e => e.Name)) #>)<#= code.Fragment(joinKeyFluentApiCalls, indent: 7) #>;
<#
var joinEntityTypeFluentApiCalls = joinEntityType.GetFluentApiCalls(annotationCodeGenerator);
if (joinEntityTypeFluentApiCalls != null)
{
usings.AddRange(joinEntityTypeFluentApiCalls.GetRequiredUsings());
#>
j<#= code.Fragment(joinEntityTypeFluentApiCalls, indent: 7) #>;
<#
}

foreach (var index in joinEntityType.GetIndexes())
{
var indexFluentApiCalls = index.GetFluentApiCalls(annotationCodeGenerator);
if (indexFluentApiCalls != null)
{
usings.AddRange(indexFluentApiCalls.GetRequiredUsings());
}
#>
j.HasIndex(<#= code.Literal(index.Properties.Select(e => e.Name).ToArray()) #>, <#= code.Literal(index.GetDatabaseName()) #>)<#= code.Fragment(indexFluentApiCalls, indent: 7) #>;
<#
}
#>
});
<#
anyEntityTypeConfiguration = true;
}

// If any significant code was generated, append it to the main environment
if (anyEntityTypeConfiguration)
{
mainEnvironment.Append(GenerationEnvironment);
anyConfiguration = true;
}

// Resume generating code into the main environment
GenerationEnvironment = mainEnvironment;
}

if (anyConfiguration)
{
WriteLine("");
}
#>
OnConfigurePartial(entity);
}

partial void OnConfigurePartial(EntityTypeBuilder<<#= EntityType.Name #>> modelBuilder);
}
<#
mainEnvironment = GenerationEnvironment;
GenerationEnvironment = new StringBuilder();

foreach (var ns in usings.Distinct().OrderBy(x => x, new NamespaceComparer()))
{
#>
using <#= ns #>;
<#
}

WriteLine("");

GenerationEnvironment.Append(mainEnvironment);
#>
8 changes: 8 additions & 0 deletions samples/efcpt-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,14 @@
false
]
},
"use-t4-split": {
"type": "boolean",
"default": false,
"title": "Customize code using T4 templates including EntityTypeConfiguration.t4. This cannot be used in combination with use-t4 or split-dbcontext-preview",
"examples": [
false
]
},
"t4-template-path": {
"type": [ "string", "null" ] ,
"default": null,
Expand Down
2 changes: 1 addition & 1 deletion src/Core/RevEng.Core.60/IReverseEngineerScaffolder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace RevEng.Core
{
public interface IReverseEngineerScaffolder
{
SavedModelFiles GenerateDbContext(ReverseEngineerCommandOptions options, List<string> schemas, string outputContextDir, string modelNamespace, string contextNamespace, string projectPath, string outputPath);
SavedModelFiles GenerateDbContext(ReverseEngineerCommandOptions options, List<string> schemas, string outputContextDir, string modelNamespace, string contextNamespace, string projectPath, string outputPath, string rootNameSpace);
SavedModelFiles GenerateFunctions(ReverseEngineerCommandOptions options, List<string> schemas, ref List<string> errors, string outputContextDir, string modelNamespace, string contextNamespace, bool supportsFunctions);
SavedModelFiles GenerateStoredProcedures(ReverseEngineerCommandOptions options, List<string> schemas, ref List<string> errors, string outputContextDir, string modelNamespace, string contextNamespace, bool supportsProcedures);
}
Expand Down
31 changes: 26 additions & 5 deletions src/Core/RevEng.Core.60/ReverseEngineerRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,14 @@ public static ReverseEngineerResult GenerateFiles(ReverseEngineerCommandOptions

try
{
SavedModelFiles filePaths = scaffolder!.GenerateDbContext(options, schemas, outputContextDir, modelNamespace, contextNamespace, options.ProjectPath, options.OutputPath);
SavedModelFiles filePaths = scaffolder!.GenerateDbContext(options, schemas, outputContextDir, modelNamespace, contextNamespace, options.ProjectPath, options.OutputPath, options.ProjectRootNamespace);

#if CORE70 || CORE80
if (options.UseT4)
if (options.UseT4 || options.UseT4Split)
{
foreach (var paths in GetAlternateCodeTemplatePaths(options.ProjectPath))
{
scaffolder!.GenerateDbContext(options, schemas, paths.Path, modelNamespace, contextNamespace, paths.Path, paths.OutputPath);
scaffolder!.GenerateDbContext(options, schemas, paths.Path, modelNamespace, contextNamespace, paths.Path, paths.OutputPath, options.ProjectRootNamespace);
}
}
#endif
Expand Down Expand Up @@ -139,20 +139,25 @@ public static ReverseEngineerResult GenerateFiles(ReverseEngineerCommandOptions
}

RemoveFragments(filePaths.ContextFile, options.ContextClassName, options.IncludeConnectionString, options.UseNoDefaultConstructor);
if (!options.UseHandleBars && !options.UseT4)
if (!options.UseHandleBars && !options.UseT4 && !options.UseT4Split)
{
PostProcess(filePaths.ContextFile, options.UseNullableReferences);
}

entityTypeConfigurationPaths = SplitDbContext(filePaths.ContextFile, options.UseDbContextSplitting, contextNamespace, options.UseNullableReferences, options.ContextClassName);

if (options.UseT4Split)
{
entityTypeConfigurationPaths.AddRange(MoveConfigurationFiles(filePaths.AdditionalFiles));
}
}
else if (options.Tables.Exists(t => t.ObjectType == ObjectType.Procedure)
|| options.Tables.Exists(t => t.ObjectType == ObjectType.ScalarFunction))
{
warnings.Add("Selected stored procedures/scalar functions will not be generated, as 'Entity Types only' was selected");
}

if (!options.UseHandleBars && !options.UseT4)
if (!options.UseHandleBars && !options.UseT4 && !options.UseT4Split)
{
foreach (var file in filePaths.AdditionalFiles)
{
Expand Down Expand Up @@ -323,6 +328,22 @@ private static List<string> SplitDbContext(string contextFile, bool useDbContext
return DbContextSplitter.Split(contextFile, contextNamespace, supportNullable, dbContextName);
}

// If we didn't split, we might have used EntityTypeConfiguration.t4. In that case, <ModelName>Configuration.cs files were generated.
private static List<string> MoveConfigurationFiles(IList<string> files)
{
var configurationFiles = files.Where(x => x.EndsWith("Configuration.cs", StringComparison.InvariantCulture)).ToList();

var movedFiles = new List<string>();
foreach (var configurationFile in configurationFiles)
{
var newFileName = Path.Combine(Path.GetDirectoryName(configurationFile) ?? string.Empty, "Configurations", Path.GetFileName(configurationFile));
File.Move(configurationFile, newFileName, overwrite: true);
movedFiles.Add(newFileName);
}

return movedFiles;
}

private static void RemoveFragments(string contextFile, string contextName, bool includeConnectionString, bool removeDefaultConstructor)
{
if (string.IsNullOrEmpty(contextFile))
Expand Down
7 changes: 4 additions & 3 deletions src/Core/RevEng.Core.60/ReverseEngineerScaffolder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ public SavedModelFiles GenerateDbContext(
string modelNamespace,
string contextNamespace,
string projectPath,
string outputPath)
string outputPath,
string rootNameSpace)
{
ArgumentNullException.ThrowIfNull(options);

Expand All @@ -77,15 +78,15 @@ public SavedModelFiles GenerateDbContext(

ContextName = code.Identifier(options.ContextClassName),
ContextDir = outputContextDir,
RootNamespace = null,
RootNamespace = rootNameSpace,
ContextNamespace = contextNamespace,
ModelNamespace = modelNamespace,
SuppressConnectionStringWarning = false,
ConnectionString = options.ConnectionString,
SuppressOnConfiguring = !options.IncludeConnectionString,
UseNullableReferenceTypes = options.UseNullableReferences,
#if CORE70 || CORE80
ProjectDir = options.UseT4 ? (options.T4TemplatePath ?? projectPath) : null,
ProjectDir = (options.UseT4 || options.UseT4Split) ? (options.T4TemplatePath ?? projectPath) : null,
#endif
};

Expand Down
Loading