Scaffolded Item Visual Studio For Mac
Missing New Scaffolded Item. Visual studio 2017 version 15.9 preview windows 10.0 centrico reported Sep 08, 2018 at 11:47 PM.
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.
Update (.NET Core 2.1+): This entry has been revised for .NET SDK Version 2.2.300.
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.
- Update (.NET Core 2.1+): For .NET Core 2.1+ we need to install a tool. If you are using .NET Core 2.0, you can ignore this step. Please run the following command:
dotnet tool install -g dotnet-aspnet-codegenerator
This will install the dotnet-aspnet-codegenerator tool as a global tool (-g). You only need to do this step once per machine.
- 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:
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 data 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 -udlwe 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.
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. This feature was introduced in MySQL Connector/NET 6.10.2-beta and 8.0.8-dmr; however, scaffolding is not supported with all versions of Connector/NET (see Table 8.2, “Supported versions of Entity Framework Core”).
The Design
package for scaffolding a database is part of the main package in EF Core 2.0 (or later) and no longer separate. If you are upgrading from EF Core 1.1 to EF Core 2.0 or 2.1, you must remove the MySql.Data.EntityFrameworkCore.Design
package manually.
NuGet packages have the ability to select the best target for a project, which means that NuGet will install the libraries related to that specific framework version.
There are two different ways to scaffold an existing database:
This section shows how to scaffold the sakila
database using both approaches.
Any implementation of .NET Standard (see https://dotnet.microsoft.com/platform/dotnet-standard#versions)
Visual Studio 2017 version 15.7 (required for Using Package Manager Console in Visual Studio)
MySQL Server 5.7
sakila
database sample (see https://dev.mysql.com/doc/sakila/en/)
When upgrading ASP.NET Core applications to a newer framework, be sure to use the appropriate EF Core version (see https://docs.microsoft.com/en-us/aspnet/core/migration/30-to-31?view=aspnetcore-3.1).
Initialize a valid .NET Core project and console application using the .NET Core command-line interface (CLI) and then change to the newly created folder (
sakilaConsole
).Add the MySQL NuGet package for EF Core using the CLI. For example, use the following command to add the
MySql.Data.EntityFrameworkCore v8.0.20
package:The version (for example,
--version 8.0.20
) must match the actual Connector/NET version you are using. For current version information, see Table 8.2, “Supported versions of Entity Framework Core”.Add the following
Microsoft.EntityFrameworkCore.Design
Nuget package:EF Core 2.0 only: Add a reference to
Microsoft.EntityFrameworkCore.Tools.DotNet
as aDotNetCliToolReference
entry in thesakilaConsole.csproj
file as follows:The .NET tools are included in the .NET Core 2.1 SDK (and later) and are not required or supported for EF Core 2.1. If this is an upgrade, remove the following reference to that package from the .
csproj
file (version 2.0.3 in this example) :Restore dependencies and project-specific tools that are specified in the project file as follows:
Create the Entity Framework Core model by executing the following command (adjust the connection-string values to match your settings for the
user=
andpassword=
options):To validate that the model has been created, open the new
sakila
folder. You should see files corresponding to all tables mapped to entities. In addition, look for thesakilaContext.cs
file, which contains theDbContext
for this database.
Scaffolding a Database Using Package Manager Console in Visual Studio
Open Visual Studio and create a new Console App (.NET Core) for C#.
Add the MySQL NuGet package for EF Core using the Package Manager Console. For example, use the following command to add the
MySql.Data.EntityFrameworkCore v8.0.20
package:The version (for example,
-Version 8.0.20
) must match the actual Connector/NET version you are using. For current version information, see Table 8.2, “Supported versions of Entity Framework Core”.Install the following NuGet packages by selecting either Package Manager Console or Manage NuGet Packages for Solution from the Tools and then NuGet Package Manager menu:
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools version 2.0.3
(for EF Core 2.0)The .NET tools are included in the .NET Core 2.1 SDK (and later) and are not required or supported for EF Core 2.1. If this is an upgrade, remove the reference to that package from the .
csproj
file (version 2.0.3 in this example) :
Open Package Manager Console and enter the following command at the prompt to create the entities and
DbContext
for thesakila
database (adjust the connection-string values to match your settings for theuser=
andpassword=
options):Visual Studio creates a new
sakila
folder inside the project, which contains all the tables mapped to entities and thesakilaContext.cs
file.
It is possible to specify the exact tables in a schema to use when scaffolding database and to omit the rest. The command-line examples that follow show the parameters needed for filtering tables.
.NET Core CLI:
Package Manager Console in Visual Studio:
When scaffolding a database, you can use more than one schema or database. Note that the account used to connect to the MySQL server must have access to each schema to be included within the context. Multiple-schema functionality was introduced in Connector/NET 6.10.3-rc and 8.0.9-dmr releases.
The following command-line examples show how to incorporate the sakila
and world
schemas within a single context.
.NET Core CLI:
Package Manager Console in Visual Studio: