efcore icon indicating copy to clipboard operation
efcore copied to clipboard

DesignTimeServices recommended way to modify scaffolding output

Open MariovanZeist opened this issue 4 years ago • 2 comments

I use designtime overrides to manipulate DbContext scaffolding.

With net6.0 I used the below code to modify the Generated DbContext source

public class CustomEFDesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
    {
     //....
     serviceCollection.AddSingleton<ICSharpDbContextGenerator, CustomDbContextGenerator>();
    }
}

public class CustomDbContextGenerator : CSharpDbContextGenerator
{
    public CustomDbContextGenerator(IProviderConfigurationCodeGenerator providerConfigurationCodeGenerator, IAnnotationCodeGenerator annotationCodeGenerator, ICSharpHelper cSharpHelper) : base(providerConfigurationCodeGenerator, annotationCodeGenerator, cSharpHelper)
    {
    }

    public override string WriteCode(IModel model, string contextName, string connectionString, string contextNamespace, string modelNamespace, bool useDataAnnotations, bool useNullableReferenceTypes, bool suppressConnectionStringWarning, bool suppressOnConfiguring)
    {
        var code = base.WriteCode(model, contextName, connectionString, contextNamespace, modelNamespace,useDataAnnotations, useNullableReferenceTypes, suppressConnectionStringWarning, suppressOnConfiguring);
        //Do some 'Magic' string replacement here
        return code;
    }
}

But this no longer works with net7.0 Do you have a suggestion how to get this working in net7.0?

EF Core version: 7.0 Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) Target framework: (e.g. .NET 7.0) IDE: (e.g. Visual Studio 2022 17.4)

MariovanZeist avatar Nov 11 '22 16:11 MariovanZeist

Use the T4 templates?

ErikEJ avatar Nov 11 '22 18:11 ErikEJ

@ErikEJ That works like a charm. A great addition to EfCore. Thanks for pointing it out to me.

MariovanZeist avatar Nov 12 '22 09:11 MariovanZeist