Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core - Customise Scaffolding

In Entity Framework 6 we can add the T4 templates the scaffolding uses by running

Install-Package EntityFramework.CodeTemplates.CSharp

But in Entity Framework Core the scaffolding system does not appear to use T4 templates, nor does it seem like the scaffolding can be customised. It seems to be all in c# classes eg.

https://github.com/aspnet/EntityFramework/blob/a508f37cf5a0246e9b92d05429153c3d817ad5ec/src/Microsoft.EntityFrameworkCore.Tools.Core/Scaffolding/Internal/EntityTypeWriter.cs

Is there any way to customise the output from the scaffold?

like image 723
user917170 Avatar asked Jun 07 '16 12:06

user917170


People also ask

What is scaffolding in Entity Framework Core?

Scaffolding a database produces an Entity Framework model from an existing database. The resulting entities are created and mapped to the tables in the specified database. For an overview of the requirements to use EF Core with MySQL, see Table 7.2, “Connector/NET Versions and Entity Framework Core Support”).

What is Scaffold-DbContext command?

The above Scaffold-DbContext command creates entity classes for each table in the SchoolDB database and context class (by deriving DbContext ) with Fluent API configurations for all the entities in the Models folder. The following is the generated Student entity class for the Student table.


1 Answers

There is a special, yet-to-be-documented hook to override design-time services:

class Startup
{
    public static void ConfigureDesignTimeServices(IServiceCollection services)
        => services.AddSingleton<EntityTypeWriter, MyEntityTypeWriter>();
}

Then implement your custom generator.

class MyEntityTypeWriter : EntityTypeWriter
{
    public EntityTypeWriter(CSharpUtilities cSharpUtilities)
        : base(cSharpUtilities)
    {
    }

    // TODO: Override with custom implementation
}

Update: See Yehuda Goldenberg's answer for another way to do this in EF Core 1.0.2+.

like image 199
bricelam Avatar answered Oct 06 '22 01:10

bricelam