dotnet / EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
https://docs.microsoft.com/ef/
Creative Commons Attribution 4.0 International
1.63k stars 1.96k forks source link

Document how to share T4 templates across projects #4292

Open gao-artur opened 1 year ago

gao-artur commented 1 year ago

Before EF Core 7, we used to override the ICSharpDbContextGenerator implementation in the IDesignTimeServices to customize the DbContext generation during the scaffold. Starting EF Core 7, this approach no longer works, and we are now exploring the t4 templates approach.

We have many (~15) DB to scaffold. Their models will be located in different folders, but they all need the same template. We have a single Scaffold.Console app, where we implemented our customizations, and it uses as a startup project during the scaffold. Unfortunately, putting the templates in the startup project folder doesn't work. It works only when templates are located in the destination folder (the folder where we write the generated files).

I have seen this issue, which was closed as Won't do. Any suggestion on how to reuse the same template without copying it 15 times and synchronizing the changes on every update?

ErikEJ commented 1 year ago

Linked files?

gao-artur commented 1 year ago

Tried it. But template files should be physically located in the destination folder.

gao-artur commented 1 year ago

https://github.com/dotnet/efcore/blob/767bc93c6e6fca19868f486c7df8f4235bcf53cd/src/EFCore.Design/Scaffolding/Internal/TextTemplatingModelGenerator.cs#L103

ajcvickers commented 1 year ago

@gao-artur You can reference a shared copy of the template file from within the template file of each project. For example, the contents of "MyProject\CodeTemplates\EFCore\DbContext.t4" would be

<#@ include file="C:\local\CodeTemplates\EFCore\DbContext.t4" #>

Or, with relative paths:

<#@ include file="..\..\..\..\..\CodeTemplates\EFCore\DbContext.t4" #>

And then "C:\local\CodeTemplates\EFCore\DbContext.t4" is the actual T4 template that you want to use in multiple places. Likewise for "EntityType.t4".

gao-artur commented 1 year ago

@ajcvickers, thank you! It worked!