Handlebars templates for different datacontexts

404 Views Asked by At

I have two database contexts in the same project that look different. One inherits from a different base class and has a different constructor.

public partial class DbFirstGraphQLDataContext : DbContext
    {
        public DbFirstGraphQLDataContext(DbContextOptions options) : base(options)
        {
        }

and

public partial class DbFirstOtherDataContext : DbContextCustomBase
    {
        public DbFirstGraphQLDataContext(DbContextOptions options, IServiceCollection serviceCollection) : base(options, serviceCollection)
        {
        }

I can scaffold one of them first using the typical command: dotnet ef dbcontext scaffold -c DbFirstGraphQLDataContext ...

I have the basic scaffolding design time services:

    public class ScaffoldingDesignTimeServices : IDesignTimeServices
    {
        public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
        {
            serviceCollection.AddHandlebarsScaffolding(opts=> opts.TemplateData);
        }
     }

And the .hbs file, of which I have pasted part of it. As you can see the .hbs file is for the DbFirstGraphQLDataContext

{{> dbimports}}
using DA.SomeInternalRepo;

namespace {{namespace}}
{
    //This file is autogenerated using EF database first. Do not modify it. Customisations can be made using the .hbs template files
    public partial class {{class}} : DbContextCustomBase
    {

How might I write the template, C# code or script parameters so that it renders a different constructor or base class depending on which context is being rendered

1

There are 1 best solutions below

0
James Joyce On BEST ANSWER

In the AddHandlebarsScaffolding call, add your base class into the TemplateData:

options.TemplateData = new Dictionary<string, object>
{    
    { "base-class", "MyBaseClass" }
};

Then in your "Class.hbs" template, add this reference

public partial class {{class}} : {{base-class}}

And build... It will use the base class you define. Set it per context you need to generate...