2017年3月23日 星期四

[ASP.NET Core] Use CodeGeneration.Tools commands

 ASP.NET Core    CodeGeneration.Tools   aspnet-codegenerator

Introduction


Microsoft.VisualStudio.Web.CodeGeneration.Tools is used for code generation (Scaffolding) in ASP.NET Core. It contains the dotnet-aspnet-codegenerator commands for generating controllers and views. 




Environment

Dotnet CLI 1.0.0


Commands


Create Controller :

Show help

dotnet aspnet-codegenerator controller -?


Generate MVC Controller

dotnet aspnet-codegenerator controller -name <YourControllerName> -outDir Controllers


Generate Api Controller

dotnet aspnet-codegenerator controller -name <YourControllerName> -api -outDir Controllers


PS. <YourControllerName> do not need a postfix: “Controller”, in other words, if you would like to have LoginController, then just type “Login” as <YourControllerName>.

For example, the following command will generate LoginController.cs in “Contollers” folder,

$> dotnet aspnet-codegenerator controller -name Login -outDir Controllers

And the following command will force(overwrite) generate one in “Areas\Controllers”,

$> dotnet aspnet-codegenerator controller -name Login -f -outDir Areas\Controllers


Or generate with actions: Index | Details | Create | Edit | Delete

dotnet aspnet-codegenerator controller -name <YourControllerName> -actions -outDir Controllers


And for those who already have Model and DbContext:

dotnet aspnet-codegenerator controller –name <YourControllerName>  -m <YourViewModel> -dc <YourDbContext> -outDir Controllers


Create MVC View :

Show help

dotnet aspnet-codegenerator view -?


Generate

Notice that a viewModel is required, or we will get the error:
Cannot perform runtime binding on a null reference.

dotnet aspnet-codegenerator view <YourViewName> <TemplateName> -m <YourViewModel> -outDir Views\<YourControllerName>

Template name includes: Empty | List | Create | Edit | Delete | Details


Furthermore, we can use the default Layout on view,

dotnet aspnet-codegenerator view <YourViewName> <TemplateName> -m <YourViewModel> -outDir –udl Views\<YourControllerName>


 Or specify certain Layout like this.
dotnet aspnet-codegenerator view <YourViewName> <TemplateName> -m <YourViewModel> -outDir –l <LayoutName> Views\<YourControllerName>



For example, the following command will create a view named “CreateNew.cshtml” with Create template, default Layout and UserViewModel in path Views\Account.

$> dotnet aspnet-codegenerator view CreateNew create -m UserViewModel -udl -outDir Views\Account


Reference



沒有留言:

張貼留言