ASP.NET Core 2: Doing scaffolding with dotnet CLI | aspnet-CodeGenerator

The dotnet CLI (Command-line interface) is a powerful tool which allows us to work with .NET projects without using Visual Studio. With dotnet CLI we can: generate projects, solutions, add nuget packages, run projects, publish them, among others. This is a cross-platform tool, which means that we can use it in Windows, Linux and MacOS.

In addition to creating projects with the dotnet CLI, such as ASP.NET MVC or Web API projects, we can generate some of the parts of these projects, such as controllers and views. We call this scaffolding: the generation of areas, controllers, views and pages with predefined code. Visual Studio helps us a lot with scaffolding, however, how can we do scaffolding with the dotnet CLI? In this post we will answer this question with some examples.

In this post I will work on Windows 10, with the .net SDK version 2.1.104.

We will do Scaffolding in an ASP.NET Core MVC project. Although, what you learn in this post you can apply in Razor Pages based projects and Web API’s.

Creating the project

First, we will learn how to configure a project from scratch which will be able to use the aspnet-codeGenerator command. This is the command which will allow us to do scaffolding. Later in this post we will use a github project to make examples.

Let’s then create an example project and configure it:

  • Open a terminal
  • Go to the directory where you want to create your project
  • Write the following commands to create an MVC project:

dotnet new mvc -o mvcApp

cd mvcApp

The first command creates a mvc project (dotnet new mvc) and places the resulting files in a folder called mvcApp (-o mvcApp). With the second command we enter the folder in the terminal.

  • Use the following command to install the nuget package that allows us to perform scaffolding, and then make a build:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design

dotnet build

Do not be confused with the name of the package, you do not need Visual Studio to use it.

  • To verify that we have installed everything successfully, run the following command:

dotnet aspnet-codegenerator -h

This should display the following message in the console:

Usage: aspnet-codegenerator [arguments] [options]

Arguments: generator Name of the generator. Check available generators below.

Options:
-p|–project Path to .csproj file in the project.
-n|–nuget-package-dir
-c|–configuration Configuration for the project (Possible values: Debug/ Release)
-tfm|–target-framework Target Framework to use. (Short folder name of the tfm. eg. net46)
-b|–build-base-path
–no-build

Available generators:
area : Generates an MVC Area.
controller: Generates a controller.
razorpage : Generates RazorPage(s).
view : Generates a view.

As we can see, we have generators to work with areas, controllers, razorpages, and views. You are now free to start using the aspnet-codegenerator command to do scaffolding.

From now on, we will work with the following project, the idea is that that project has a context and a model that we will use for scaffolding:

https://github.com/gavilanch/example-scaffolding-with-dotnet-cli

You just have to download the code in your machine, and then go to the project folder in the terminal.

Doing Controller Scaffolding

Let’s see the options we have when making a controller with scaffolding. If we write the command:

dotnet aspnet-codegenerator controller -h

We will get the following help:

Options:
-p|–project Path to .csproj file in the project.
-n|–nuget-package-dir
-c|–configuration Configuration for the project (Possible values: Debug/ Release)
-tfm|–target-framework Target Framework to use. (Short folder name of the tfm. eg. net46)
-b|–build-base-path
–no-build

Selected Code Generator: controller

Generator Options:
–controllerName|-name : Name of the controller
–useAsyncActions|-async : Switch to indicate whether to generate async controller actions
–noViews|-nv : Switch to indicate whether to generate CRUD views –restWithNoViews|-api : Specify this switch to generate a Controller with REST style API, noViews is assumed and any view related options are ignored
–readWriteActions|-actions : Specify this switch to generate Controller with read/write actions when a Model class is not used
–model|-m : Model class to use –dataContext|-dc : DbContext class to use
–referenceScriptLibraries|-scripts : Switch to specify whether to reference script libraries in the generated views –layout|-l : Custom Layout page to use
–useDefaultLayout|-udl : Switch to specify that default layout should be used for the views
–force|-f : Use this option to overwrite existing files
–relativeFolderPath|-outDir : Specify the relative output folder path from project where the file needs to be generated, if not specified, file will be generated in the project folder
–controllerNamespace|-namespace : Specify the name of the namespace to use for the generated controller

As we can see, we have many options, we can indicate the name of the controller, if it will use asynchronous methods, if it will not use views (useful for web api), the model, the context, in short, we have options to make the controller we need. Let’s see first a simple example. We will generate an api-style controller, without views, with write and read actions:

dotnet aspnet-codegenerator controller -name ExampleController -actions -api            -outDir Controllers

That should create a controller called ExampleController in the Controllers folder.

Now let’s involve a model. We are going to generate a controller, which is not API style, without views, with writing and reading actions focused on a given model. In the case of the project we are working on, the model is called Person, and the context is called ApplicationDbContext:

dotnet aspnet-codegenerator controller -name PeopleController -actions -nv -m Person -dc ApplicationDbContext -outDir Controllers

Of course, when you are scaffolding a Controller, you can generate all the views for the different viewTemplates (Create, List, Edit, etc.), you just don’t specify the -nv options. So for example, in the previous case, if you also would like to create the views, just do it like this:

dotnet aspnet-codegenerator controller -name PeopleController -actions -m Person -dc ApplicationDbContext -outDir Controllers

Please notice that all I did was to remove the -nv option. But let’s say that for some reason, you want to generate the views yourself. Let’s see how to scaffold Views.

Doing Views Scaffolding

Let’s see the options we have when it comes to scaffolding the views. Let’s run the following command:

dotnet aspnet-codegenerator view -h

This will show us the following options:

Generator Arguments:
viewName : Name of the view
templateName : The view template to use, supported view templates: ‘Empty|Create|Edit|Delete|Details|List’

Generator Options:
–model|-m : Model class to use
–dataContext|-dc : DbContext class to use
–referenceScriptLibraries|-scripts : Switch to specify whether to reference script libraries in the generated views
–layout|-l : Custom Layout page to use
–useDefaultLayout|-udl : Switch to specify that default layout should be used for the views
–force|-f : Use this option to overwrite existing files
–relativeFolderPath|-outDir : Specify the relative output folder path from project where the file needs to be generated, if not specified, file will be generated in the project folder
–controllerNamespace|-namespace : Specify the name of the namespace to use for the generated controller
–partialView|-partial : Generate a partial view, other layout options (-l and -udl) are ignored if this is specified

As we can see, we have options to decide the template that we want to use in case we are going to work with a model, we can also indicate the layout to be used, or if we want to create a partial view.

Let’s start by creating a simple view in the Views / Home folder:

dotnet aspnet-codegenerator view myView Empty -udl -outDir Views / Home

Notice that we use the name of the view as “myView”, the template is “Empty”, with the   -udl we indicate that we want to use the default layout, and finally with -outDir we indicate where we want to place the view.

Now, we are going to create a view which uses our Person model, we will use the Create template:

dotnet aspnet-codegenerator view Create Create -outDir Views / Person -udl -m Person

We see that the command creates a view called Create, with Create template (hence the two “Create”, the first is the name of the view, the second Create is the template to use), then indicates that the view is going to be placed in Views/Person, after that, with -udl it is indicated that we will use the default layout, and finally, with -m, we indicate that we want to use the Person model.

Delete the Create view that has just been created, because we will create it again.

Imagine now that you want to create a view for each template (except Empty) for a specific model, it would be very tedious to have to execute the previous command for each of the templates. Something we can do is create a simple file with extension cmd which receives as parameter the name of the model, and with this information, run all commands to create each of the views. This is the content of the batch:

dotnet build
dotnet aspnet-codegenerator view Create Create -udl -outDir Views /% 1 -m% 1 –no-build
dotnet aspnet-codegenerator view Edit Edit -udl -outDir Views /% 1 -m% 1 –no-build
dotnet aspnet-codegenerator view Delete Delete -udl -outDir Views /% 1 -m% 1 –no-build
dotnet aspnet-codegenerator view List List -udl -outDir Views /% 1 -m% 1 –no-build
dotnet aspnet-codegenerator view Details Details -udl -outDir Views /% 1 -m% 1 –no-build

It is not at all sophisticated, but the important thing is to see how we can automate our use of the dotnet CLI. The previous batch is in the github repository which we share above, the file name is dotnet-scaffold.cmd. If you have it, you can execute it in the following way:

dotnet scaffold Person

Where Person is the name of the model to be used. With this, all the views are created based on the Person model, in the Views/Person folder.

Summary

We can use aspnet-codegenerator to make Scaffolding of our controllers, areas, views and razor pages. We can also use batches to automate a script, or simplify a long command that we use frequently.

2 comments

  1. Hi! Just to update the upcoming readers about the “aspnet-codegenerator” because I had some troubles trying to surpass this step. The aspnet-codegenerator is a global tool now, so you may install it using “dotnet tool install dotnet-aspnet-codegenerator”. If you’re using Linux, you must also add the reference to the $PATH or directly in the .bashrc using “export PATH=”$HOME/.dotnet/tools:$PATH”. Create the scaffolding using the following command “dotnet-aspnet-codegerator controller -name ExampleController -actions -api -outDir Controllers”.

    Thank you for the tutorial!

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s