How to generate controller using dotnetcore command line
If you are using Command line, you can get scaffold features with Code Generator package. To use this, first you need to include CodeGeneration packages in project.json.
"dependencies": {
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
},
"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
"version": "1.0.0-preview2-final",
"type": "build"
}
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
"version": "1.0.0-preview2-final",
"imports": [
"portable-net45+win8"
]
}
}
Now you can restore the packages using dotnet restore
command. Once it is completed, you can scaffold controllers and views with the following command-
dotnet aspnet-codegenerator --project . controller -name HelloController -m Author -dc WebAPIDataContext
The above command will generate controller with name HelloController in the root directory, and views for CRUD options inside Hello folder under Views folder. You can use --help
commandline switch after controller parameter to get more options about controller generator.
This is the new way since mid 2018
You have to install dotnet-aspnet-codegenerator.
This is now done globally and not through a Nuget package:
PowerShell:
dotnet tool install --global dotnet-aspnet-codegenerator
Then this is how you create a REST-Controller from an existing EF Model in PowerShell:
dotnet-aspnet-codegenerator -p "C:\MyProject\MyProject.csproj" controller -name MyDemoModelController -api -m My.Namespace.Models.MyDemoModel -dc MyDemoDbContext -outDir Controllers -namespace My.Namespace.Controllers
Some helpful calls
Show available generators (-p... -h
):
dotnet-aspnet-codegenerator -p "C:\MyProject\MyProject.csproj" -h
Show available options of the "controller" generator (-p... controller -h
):
dotnet-aspnet-codegenerator -p "C:\MyProject\MyProject.csproj" controller -h
Generate controllers for many models in a loop
This is how you would generate REST controllers for all models in a given path from a PowerShell:
Get-ChildItem "C:\MyProject\Models" -Filter *.cs |
Foreach-Object {
$scaffoldCmd =
'dotnet-aspnet-codegenerator ' +
'-p "C:\MyProject\MyProject.csproj" ' +
'controller ' +
'-name ' + $_.BaseName + 'Controller ' +
'-api ' +
'-m My.Namespace.Models.' + $_.BaseName + ' ' +
'-dc MyDemoDbContext ' +
'-outDir Controllers ' +
'-namespace My.Namespace.Controllers'
# List commands for testing:
$scaffoldCmd
# Excute commands (uncomment this line):
#iex $scaffoldCmd
}