T4 Tutorial: Execute templates at build time

This is not so hard to do actually. It ensures your transformations are executed when you build your solution, when in some cases you did not click ‘Build > Transform all T4 Templates’ when changes are made to your .tt files.

If one of your projects uses T4 to generate code, and you want it to execute at build time, consider the next steps:

Unload your project

Righ-click on the project in your solution explorer and click ‘unload’.

Open the .csproj of your project

Right-click again and select ‘edit projectname.csproj’

Edit the .csproj file

Add following PropertyGroup at the beginning of your csproj file (for VS2017):

    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>

The TransformOnBuild property set tot true ensures the templates to be transformed when you build your project (false by default).

OverwriteReadOnlyOutputFiles forces overwriting of readonly output files.

Set TransformOutOfDateOnly to false to transform files even if the output is up to date.

At the end of your csproj file, add following import:

<Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" />

Now you can reload your project and you are done. All T4 Templates within this project will be executed on each build.