entity-framework-coret4

How to debug custom Entity Framework Core T4 templates


I followed this documentation on how to use custom T4 templates for generating code from a database with EF Core: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/templates

Now, as I am modifying the template, what is the best way to debug errors in the T4 file?

If I execute the scaffolding command and there is any error in the EntityType.t4 document, I only get a very generic error message:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.TextTemplatingModelGenerator.GenerateModel(IModel model, ModelCodeGenerationOptions options)

This is the scaffolding command I am using in the Visual Studio Package Manager Console: Scaffold-DbContext "Data Source=..." Microsoft.EntityFrameworkCore.SqlServer -UseDatabaseNames -Context SqlServerContext -StartupProject <...> -ContextDir Context -OutputDir Model -Tables <...>

Update: I get a useful message for errors in the DbContext.t4 file, but only the generic error noted above for errors in the EntityType.t4.


Solution

  • The simplest way to debug a template is to use the just-in-time debugger when the template is running.

    <#@ template debug="true" #>
    <#
        System.Diagnostics.Debugger.Launch();
    #>
    

    After the debugger is attached, you should be able to add breakpoints to the template code, evaluate locals, etc.

    The debug="true" part tells T4 to keep more information around for a better debugging experience.