How to scaffold multiple ASP.NET CORE MVC controllers at once using a bat file

Previously I wrote about how we can customise the templates Visual Studio uses when it scaffolds a controller.

After changing a template we can re-scaffold our controllers one by one from the GUI provided by Visual Studio…

Scaffold a controller in Visual Studio

… BUT this can be very time consuming if we want to re-scaffold a lot of controllers each time we make a change to any of the controller or view templates.

A better way is to trigger the scaffolding process for multiple controllers at once by wrapping calls to the asp.net core scaffolding engine in a bat file.

In the example below (click for a larger view in a new window) I’m scaffolding three different controllers…

Scaffolding via the command lineI’ve included a call to install the aspnet-codegenerator global tool which we need to trigger scaffolding at the top of the file. You don’t have to include this, but I like to keep it there just to make things easier for the next developer.

The command that I’ve used to scaffold the CustomersController is…

dotnet aspnet-codegenerator controller – controllerName CustomersController – model Customer – dataContext EFContext – relativeFolderPath Controllers – force – useDefaultLayout – referenceScriptLibraries – layout "~/Views/Shared/_Layout.cshtml"

The flags I’ve set match the defaults which are set when we create a scaffolded controller through the GUI. Note the inclusion of the force flag which when included means existing files will be overwritten.

Since I’ve set the relativeFolderPath flag to ‘Controllers’ this means I need to save the .bat file in the root of my project.

If you’re copying and pasting from above, note WordPress has messed up the dashes. Each flag should have two dashes in front of it… see the image example above.

Running the scaffolding bat file from within Visual Studio

We can run the bat file by double clicking it in the file system but to run it from within Visual Studio we can install the Open Command Line extension. After installing the extension we can right click the .bat file and select ‘Execute File’…

Execute File

and we’ll see the CMD window pop up with output similar to below…controller-scaffold-batfile

One thought on “How to scaffold multiple ASP.NET CORE MVC controllers at once using a bat file”

Leave a Reply

Your email address will not be published. Required fields are marked *