Scaffolding ASP.NET Core MVC

In this article, you will learn about scaffolding ASP.NET Core MVC.

In this post, we are going to explore how to create a model based on the existing database (Db-First), with the help of Entityframework Core Command then learn how to generate Controller & Views using Scaffolding (Interface & Code-Generator Command) based on model.

Here are the Topics.

  1. Manage Packages
  2. EF Core Model(DB-First)
  3. MVC Core Scaffolding

Let’s create a New Project: File > New > Project



From the left menu choose .NET Core > ASP.NET Core Web Application



Choose ASP.NET Core sample template, Click OK.



Here, the initial view of the sample template is given below in the Solution Explorer.


Create a new database, using SSMS, name it “PhoneBook”. Copy the query & run it, using query editor of SSMS.

  1. USE [PhoneBook]  
  2. GO  
  3.   
  4. /****** Object: Table [dbo].[Contacts] Script Date: 12/9/2016 2:47:49 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[Contacts](  
  12. [ContactID] [int] IDENTITY(1,1) NOT NULL,  
  13. [FirstName] [nvarchar](50) NULL,  
  14. [LastName] [nvarchar](50) NULL,  
  15. [Phone] [nvarchar](50) NULL,  
  16. [Email] [nvarchar](50) NULL,  
  17. CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED   
  18. (  
  19. [ContactID] ASC  
  20. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  21. ON [PRIMARY]  
  22.   
  23. GO  
Entity Framework Core

Entity Framework (EF) Core is data access technology, which is targeted for cross-platform. Open project.json, and add the packages given below in Dependency & Tools section.

Add Dependency Package
  1. //Database Provider for EF Core  
  2. "Microsoft.EntityFrameworkCore.SqlServer""1.0.1",  
  3.   
  4. //EF Core Package Manager Console Tools  
  5. "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final",  
  6.   
  7. //EF Core Funtionality for MSSQL Server  
  8. "Microsoft.EntityFrameworkCore.SqlServer.Design""1.0.1"  
Add Tools
  1. //Access Command Tools EF Core  
  2. "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final",  
EntityFrameworkCore.SqlServer
The database provider allows Entity Framework Core to be used with Microsoft SQL Server.

EntityFrameworkCore.SqlServer.Design
Design-time allows Entity Framework Core functionality (EF Core Migration) to be used with Microsoft SQL Server.

EntityFrameworkCore.Tools
Command line tool for EF Core that includes the commands.

For Package Manager Console.
  • Scaffold-DbContext
  • Add-Migration
  • Update-Database

For Command Window

  • dotnet ef dbcontext scaffold

Using CommandLine

In our sample Application, we are going to apply commands, using the command line.



Go to Project directory > Shift + Right Click to open Command Window.


Command

dotnet ef –help



Command

dotnet ef dbcontext scaffold "Server=DESKTOP-5B67SHH;Database=PhoneBook;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer --output-dir Models



As you can see from Solution Explorer, models folder is created with context & entities.



Generated DbContext

Finally, a full view of generated Context class is given below.

  1. public partial class PhoneBookContext: DbContext   
  2. {  
  3.     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  4.     {  
  5.       #warning To protect potentially sensitive information in your connection string, you should move it out of source code.See http: //go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.  
  6.             optionsBuilder.UseSqlServer(@ "Server=DESKTOP-5B67SHH;Database=PhoneBook;Trusted_Connection=True;");  
  7.     }  
  8.   
  9.     protected override void OnModelCreating(ModelBuilder modelBuilder)   
  10.     {  
  11.         modelBuilder.Entity < Contacts > (entity =>   
  12.         {  
  13.             entity.HasKey(e => e.ContactId)  
  14.                 .HasName("PK_Contacts");  
  15.   
  16.             entity.Property(e => e.ContactId).HasColumnName("ContactID");  
  17.   
  18.             entity.Property(e => e.Email).HasMaxLength(50);  
  19.   
  20.             entity.Property(e => e.FirstName).HasMaxLength(50);  
  21.   
  22.             entity.Property(e => e.LastName).HasMaxLength(50);  
  23.   
  24.             entity.Property(e => e.Phone).HasMaxLength(50);  
  25.         });  
  26.     }  
  27.   
  28.     public virtual DbSet < Contacts > Contacts {  
  29.         get;  
  30.         set;  
  31.     }  
  32. }  
ASP.Net MVC Core Scaffolding

We have used scaffolding in previous versions of .NET, as .NET Core is new. Sometimes it’s confusing as to how to start. Here, we will explore those issues. Open project.json and add the packages given below in Dependency & Tools section.

Add Dependency Package
  1. //Code Generators Command Generate Controller,Views  
  2. "Microsoft.VisualStudio.Web.CodeGenerators.Mvc""1.0.0-preview2-final",  
  3. "Microsoft.VisualStudio.Web.CodeGeneration.Tools""1.0.0-preview2-final",  
Add Tools
  1. //Access Command Tools Code Generation  
  2. "Microsoft.VisualStudio.Web.CodeGeneration.Tools""1.0.0-preview2-final"  
Click Save, packages will restore automatically. Well, the packages are installed to our Application. We are good to perform the next step of scaffolding, Controller & Views.

Scaffold using Interface

Right click on Controller folder > Add > New scaffolding Item



Choose the scaffold option, as to how the code will be generated.



Now provide model and context classes that are you are going to use to interact with the database, choose view options, and then click  the Add button to perform the action.



Wait for awhile, and as we can see from Solution Explorer, the views are generated.



The output messages are shown below.

C:\Program Files\dotnet\dotnet.exe aspnet-codegenerator --project "E:\Documents\Article\ScaffoldingCoreMVC\CoreMVCScaffolding\src\CoreMVCScaffolding" controller --force --controllerName ContactsController --model CoreMVCScaffolding.Models.Contacts --dataContext CoreMVCScaffolding.Models.PhoneBookContext --relativeFolderPath Controllers --controllerNamespace CoreMVCScaffolding.Controllers --useDefaultLayout
Finding the generator 'controller'...
Running the generator 'controller'...


Attempting to compile the application in memory

Attempting to figure out the EntityFramework metadata for the model and DbContext: Contacts

Added Controller : \Controllers\ContactsController.cs
Added View : \Views\Contacts\Create.cshtml
Added View : \Views\Contacts\Edit.cshtml
Added View : \Views\Contacts\Details.cshtml
Added View : \Views\Contacts\Delete.cshtml
Added View : \Views\Contacts\Index.cshtml
RunTime 00:00:07.87


Scaffold using CommandLine

We can generate this by using CommandLine by pointing project folder with Shift + Right click followed by the appearing command, and the Window will appear. Get help information by the command given below.

Command

dotnet aspnet-codegenerator --help



Let’s generate Controller & View, using the command given below, with project path, controller, and model info.

Command

dotnet aspnet-codegenerator --project
"E:\Documents\Article\ScaffoldingCoreMVC\CoreMVCScaffolding\src\CoreMVCScaffolding" controller --force --controllerName ContactsController --model CoreMVCScaffolding.Models.Contacts --dataContext CoreMVCScaffolding.Models.PhoneBookContext --relativeFolderPath Controllers --controllerNamespace CoreMVCScaffolding.Controllers –useDefaultLayout




We can see the controller & view are successfully generated using MVC model. In our sample Application, if we notice in the Error List tab , there’s a warning about moving sensitive information from DbContext.



This is the area in DbContext class, which causes the warning.
  1. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  2. {  
  3.   #warning To protect potentially sensitive information in your connection string, you should move it out of source code.See http: //go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.  
  4.         optionsBuilder.UseSqlServer(@ "Server=DESKTOP-5B67SHH;Database=PhoneBook;Trusted_Connection=True;");  
  5. }  
Let’s comment that out here in startup class. Now, add the Service by moving the connectionstring info from DbContext. Below, you may notice the code snippet that adds the Service.
  1. //This method gets called by the runtime. Use this method to add services to the container.  
  2. public void ConfigureServices(IServiceCollection services)   
  3. {  
  4.     // Add framework services.  
  5.     services.AddMvc();  
  6.   
  7.     var connection = @ "Server=DESKTOP-5B67SHH;Database=PhoneBook;Trusted_Connection=True;";  
  8.     services.AddDbContext < PhoneBookContext > (options => options.UseSqlServer(connection));  
  9. }  
If we now try to run our Application, the exception given below will occur. Here, the Exception message is given below.

InvalidOperationException

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the Application Service provider. If AddDbContext is used, ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.



It says, no database provider has been configured for this DbContext. Notice, we have used AddDbContext in ConfigureServices(IServiceCollection services) method.
  1. services.AddDbContext<PhoneBookContext>(options => options.UseSqlServer(connection));  
We didn’t pass it for DbContext. We need to add constructor given below to pass it to the base constructor for DbContext.
  1. public PhoneBookContext(DbContextOptions<PhoneBookContext> options) :  
  2. base(options)  
  3. {  
  4. }  
Now, we may run our sample Application by Ctrl+F5 or we can run it using the command given below..

Command

dotnet run



Open the Browser and go to http://localhost:5000 and finally the Application is running.

Contact List



Create New Contact



Edit Existing Contact



View Details Existing Contact


Delete Existing Contact


Hope this will help.

References
  1. https://docs.microsoft.com/en-us/ef/core/index
  2. https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet
  3. https://github.com/aspnet/EntityFramework/wiki/Roadmap
  4. https://www.codeproject.com/articles/1118189/crud-using-net-core-angularjs-webapi