Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Scaffolding ASP.Net Core MVC

0.00/5 (No votes)
9 Dec 2016 1  
In this post we are going to explore how to create model based on 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’s the Topics:

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

Let’s Create New Project: File > New > Project

From left menu choose .Net Core > ASP.Net Core Web Application

coremvc_2

Choose ASP.Net Core sample template, Click OK.

coremvc_3 Here’s the initial view of sample template in solution explorer.

coremvc_4

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

USE [PhoneBook]
GO

/****** Object:  Table [dbo].[Contacts]    Script Date: 12/9/2016 2:47:49 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Contacts](
	[ContactID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[Phone] [nvarchar](50) NULL,
	[Email] [nvarchar](50) NULL,
 CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED 
(
	[ContactID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Entity Framework Core:

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

Add Dependency Package:

//Database Provider for EF Core
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    
//EF Core Package Manager Console Tools
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    
//EF Core Funtionality for MSSQL Server
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1"

Add Tools:

//Access Command Tools EF Core
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",

EntityFrameworkCore.SqlServer: Database Provider, that allows Entity Framework Core to be used with Microsoft SQL Server. EntityFrameworkCore.SqlServer.Design: Design-time, that 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 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.

coremvc_5

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

coremvc_6 Command: dotnet ef –help

coremvc_7

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

coremvc_8

As we can see from solution explorer models folder is created with Context & Entities.

coremvc_9

Generated DbContext: Finally full view of generated Context class.

public partial class PhoneBookContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        #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.
        optionsBuilder.UseSqlServer(@"Server=DESKTOP-5B67SHH;Database=PhoneBook;Trusted_Connection=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Contacts>(entity =>
        {
            entity.HasKey(e => e.ContactId)
                .HasName("PK_Contacts");

            entity.Property(e => e.ContactId).HasColumnName("ContactID");

            entity.Property(e => e.Email).HasMaxLength(50);

            entity.Property(e => e.FirstName).HasMaxLength(50);

            entity.Property(e => e.LastName).HasMaxLength(50);

            entity.Property(e => e.Phone).HasMaxLength(50);
        });
    }

    public virtual DbSet<Contacts> Contacts { get; set; }
}

ASP.Net MVC Core Scaffolding:

We have used scaffolding in previous version of .Net, as .Net Core is new sometimes it’s getting confusing how to start, here we will explore those issues. Open project.json add below packages in Dependency & Tools section. Add Dependency Package:

//Code Generators Package Generate Controller,Views
"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": "1.0.0-preview2-final",
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": "1.0.0-preview2-final"

Add Tools:

//Access Command Tools Code Generation
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": "1.0.0-preview2-final"

Click Save, packages will restore automatically. Well packages are installed to our application, we are good to perform next step of Scaffolding Controller & Views.

Scaffold using Interface: Right Click on Controller folder > Add > New Scaffolding Item

coremvc_10

Choose the scaffold option how the code will generated.

coremvc_11

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

coremvc_12

Wait for a while as we can see from solution explorer the views are generated.

coremvc_13

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 that by using CommandLine, pointing the project folder with Shift + Right Click then command window will appear. Get help information by the following command.

Command: dotnet aspnet-codegenerator --help

coremvc_14

Let’s generate Controller & View using below command with project path, controller, 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

coremvc_15

As we can see the controller & view is successfully generated using MVC model. In our sample application if we notice in the Error List tab there’s a warning about to move sensitive information from DbContext.

coremvc_16 This is the area in DbContext class which cause the warning.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    #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.
    optionsBuilder.UseSqlServer(@"Server=DESKTOP-5B67SHH;Database=PhoneBook;Trusted_Connection=True;");
}

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 add the service.

//This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    var connection = @"Server=DESKTOP-5B67SHH;Database=PhoneBook;Trusted_Connection=True;";
    services.AddDbContext<PhoneBookContext>(options => options.UseSqlServer(connection));
}

If we now try to run our application below exception will occur. Here’s the Exception message:

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, then also ensure that your DbContext 
type accepts a DbContextOptions<TContext> object in its constructor 
and passes it to the base constructor for DbContext.

coremvc_17

It says, No database provider has been configured for this DbContext. Notice that we have used AddDbContext in ConfigureServices(IServiceCollection services) method.

services.AddDbContext<PhoneBookContext>(options => options.UseSqlServer(connection));

But we didn’t pass it for DbContext, We need to add below constructor to pass it to the base constructor for DbContext.

public PhoneBookContext(DbContextOptions<PhoneBookContext> options) :
    base(options)
{
}

Now we may run our sample application by Ctrl+f5 or we can run using below command.

Command: dotnet run

coremvc_18

Open browser Go to http://localhost:5000, finally the application is running.

Contact List

coremvc_19

Create New Contact

coremvc_20

Edit Existing Contact

coremvc_21

View Details Existing Contact

coremvc_22

Delete Existing Contact

coremvc_23

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

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here