I gave up waiting for EF Core team to add this as an option. I don't want to make and maintain my own T4 templates for this - that's nuts!
Solution for me was just to run some regex on the generated code as part of a powershell script.
fix-dbcontext.ps1
$filename=$args[0]
# load context file
$content = (Get-Content -Raw $filename)
[regex] $commentOutConstructorRegex = '(?ms)(?<=: DbContext\s*.*?)(public.*?)(?=\s*public)'
$content = $commentOutConstructorRegex.Replace($content, '// Default constructor removed', 1)
[regex] $removeOnConfiguringRegex = '(?ms)(protected override void OnConfiguring).*?(?=\s*protected)'
$content = $removeOnConfiguringRegex.Replace($content, '// Generated OnConfiguring removed', 1)
[regex] $dateCommentRegex = '(?ms)(?=\s*public partial class)'
$content = $dateCommentRegex.Replace($content, "`r`n`t// Generated " + (Get-Date).ToString() + "`r`n", 1)
$content | Out-File -Encoding UTF8 $filename
This will:
- Remove the default constructor
- Remove the
OnConfiguring
method including hardcoded connection string
- Add the date in a comment
Just run it with .\fix-dbcontext.ps1 .\MyDBContext.cs
.
You probably want to change that last line to context.txt
instead of $filename
until you're sure it does what you want.
IMPORTANT: This was tested only on EFCore templates, but if you understand my Regexes you should be able to modify it for EntityFramework if it doesn't already work.
*.Context.tt
file in EF Core database first approach. – Marvamarve