Click here to Skip to main content
12,768,063 members (45,538 online)
Click here to Skip to main content
Add your own
alternative version

Stats

10.3K views
207 downloads
42 bookmarked
Posted 28 Nov 2016

.NET Core Startup

, 29 Nov 2016 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article, we will learn about .NET Core Features & short overview on .NET Framework (existing). We will discuss about what changes were made/added in new environment of .NET Core.

Topics to be Discussed

  1. Short Overview of .NET Framework
  2. What is .NET Core?
  3. What is ASP.NET Core?
  4. How to Start?
  5. Detailed Overview of Initial Sample Application
    1. Global.json
    2. Properties
    3. wwwroot
    4. Controller
    5. Views
    6. appsettings.json
    7. bower.json
    8. bundleconfig.json
    9. program.cs
    10. project.json
    11. startup.cs
    12. web.config
  6. Working with Data Using
    1. ASP.NET Core &
    2. Entity Framework-7 (Core)
    3. MVC-6 (Core)

Ok, let’s start with one topic at a time to clarify our thoughts on the magical world of .NET.

.NET Framework

The .NET Framework (pronounced dot net) is a software development platform developed by Microsoft. It provides tools and libraries that allow developers to develop applications. Microsoft started development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2001, the first beta versions of .NET 1.0 were released.

.NET Framework Releases

Here, I have provided a short overview of .NET Framework Version evaluation that all we knew about, but it was just recapping for a better understand of .NET thinking & road-map.

So far, we know all these releases, but what about the new announcement? Is .NET Core another framework? Ok, let’s just take it easy, Step by step, we will uncover all those issues.

.NET Today

Microsoft has announced a lots of exciting new innovations that are included with .NET in this year. Among them, the most powerful is open source cross-platform development (Any developer, Any app, Any platform). Learn more

.NET Core

Simply .NET Core is modern, lightweight, high performance modular platform for creating web apps and RESTful APIs that run on Cross-Platform (Windows, Linux and Mac). It is a smaller set/sub-set of .NET Framework (Full), that is maintained by Microsoft & the .NET community on GitHub.

.NET Core Facilities

  • Cross-platform that runs on Windows, macOS and Linux
  • Open source
  • Command-line tools that can be exercised at the command-line
  • Compatible with .NET Framework, Xamarin and Mono, via the.NET Standard Library
  • Flexible deployment

Learn more about .NET Core …

.NET Core Platform: The .NET Core platform is made up of several components:

  1. CoreFX - .NET Core foundational libraries
  2. CoreCLR - .NET Core runtime
  3. CLI - .NET Core command-line tools
  4. Roslyn - .NET Compiler Platform

Diagram of .NET Core vs .NET Framework

.NET Core Releases

  1. .NET Core 1.1 released on 11/16/2016
  2. .NET Core 1.0 Preview 1 released on 10/24/2016
  3. .NET Core 0.1 released on 9/13/2016
  4. .NET Core 0.0 released on 6/27/2016
  5. .NET Core RC2(Release Candidate) released on 5/16/2016
  6. .NET Core RC1(Release Candidate) released on 11/18/2015

Download the latest .NET Core SDK (Runtime + Command line Tool) or Only Runtime.

.NET Core Supports

Initially, .NET Core supports four types of application development, among them, we will focus on ASP.NET Core application development.

  1. NET Core web apps
  2. Command-line apps
  3. Libraries, and
  4. Universal Windows Platform (UWP) apps

ASP.NET Core

ASP.NET Core is re-written new open source ASP.NET web framework for building web based application (web apps, IoT apps & mobile backends) that run on both full .NET Framework and .NET Core.

ASP.NET Core Facilities

  1. Developed and run on Cross Platform (Windows, Mac and Linux)
  2. Open Source
  3. Built on the .NET Core runtime & also on .NET Framework
  4. Facility of dynamic compilation
  5. Built in Dependency Injection (DI)
  6. MVC & Web API Controller are unified, Inherited from same base class
  7. New light-weight and modular HTTP request pipeline
  8. Ability to host on IIS or self-host in own process
  9. Ships entirely as NuGet packages
  10. Smart tooling like (Bower, Grunt & Gulp)

Learn more about ASP.NET Core.

How to Start?

Here is the quick installation guide for Windows.

Steps

  1. Install Visual Studio 2015 (provides a full-featured development environment)
  2. Make sure you have Visual Studio 2015 Update 3
  3. Install the .NET Core tools preview for Visual Studio
  4. Create a new .NET Core project
  5. Run the application

Learn more about how to get started…

Anatomy of ASP.NET Core Initial Application

Global.json

It is a JSON schema for the ASP.NET global configuration files, and contains the Solution information/metadata. In this file, we can configure the sdk with version, architecture or runtime that specifies which processor architecture to target, which runtime to target. Let’s get the properties in details.

  1. Projects: Specify the folders to search that contain the project
  2. Packages: Specify the package location
  3. Sdk: Specify information about the SDK

Here are our global.json properties by default.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-003131"
  }
}

To get other’s properties information details, go to > http://json.schemastore.org/global

"properties": {
  "projects": {
    "type": "array",
    "description": 
    "A list of project folders relative to this file.",
    "items": {
      "type": "string"
    }
  },
  "packages": {
    "type": "string",
    "description": "The location to store packages"
  },
  "sdk": {
    "type": "object",
    "description": "Specify information about the SDK.",
    "properties": {
      "version": {
        "type": "string",
        "description": "The version of the SDK to use."
      },
      "architecture": {
        "enum": [ "x64", "x86" ],
        "description": 
        "Specify which processor architecture to target."
      },
      "runtime": {
        "enum": [ "clr", "coreclr" ],
        "description": "Chose which runtime to target."
      }
    }
  }
}

Properties > launchSettings.json

JSON schema for the ASP.NET DebugSettings.json files. This is where we can configure our debug profile by using IDE interface, another way to set properties is launchSetting.json file. Right click on Project Properties > Debug.

Here’s the configuration properties by default in launchSetting.json.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:17023/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "CoreMVC": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

We can add another profile as production to the json file using the same command as IISExpress. Based on this environment profile, we can show hide HTML tags on different environment mood, which is known as working with multi environment. Later, we will discuss about it.

"IIS Production": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Production"
  }
}

The new debug profile will appear like the below image:

Let’s get the properties in details:

  1. commandLineArgs: The arguments to pass to the command
  2. workingDirectory: Sets the working directory of the command
  3. launchBrowser: Set to true if the browser should be launched
  4. launchUrl: The relative URL to launch in the browser
  5. environmentVariables: Set the environment variables as key/value pairs
  6. sdkVersion: Sets the version of the SDK

To get other’s properties information details, go to > http://json.schemastore.org/launchsettings.

"properties": {
  "commandLineArgs": {
    "type": "string",
    "description": "The arguments to pass to the command.",
    "default": ""
  },
  "workingDirectory": {
    "type": "string",
    "description": "Sets the working directory of the command."
  },
  "launchBrowser": {
    "type": "boolean",
    "description": "Set to true if the browser should be launched.",
    "default": false
  },
  "launchUrl": {
    "type": "string",
    "description": "The relative URL to launch in the browser.",
    "format": "uri"
  },
  "environmentVariables": {
    "type": "object",
    "description": "Set the environment variables as key/value pairs.",
    "additionalProperties": {
      "type": "string"
    }
  },
  "sdkVersion": {
    "type": "string",
    "description": "Sets the version of the SDK."
  }
}

wwwroot It’s all about serving static file directly to client. We need to serve static file. All we need to add is extension method UseStaticFiles() in startup class Configure method.

Then, resolve the dependency package "Microsoft.AspNetCore.StaticFiles": "1.0.0" for static file in project.json.

Controller

ASP.NET Core Controllers are now unified, there’s no difference between MVC Controllers (Controller base class) & WebAPI Controllers (ApiController base class). As you can see, I have put it side by side to show the difference between both MVC & WebAPI Controller, both controllers are being inherited from the same controller.

Views

ASP.NET Core MVC views are .cshtml files as we know earlier version of ASP.NET MVC views that use the Razor view engine to render views. Here, I have shown MVC folder structure and the related .cshtml files in our ASP.NET Core application.

Learn more about views & tag-helpers……

appsettings.json

This is the application configuration file that keeps the configuration value of Key/Value pair. Previously, this configuration was stored in web.config file.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

We can add the connection string to the appsetting file and then we have accessed the connection in startup.

"ConnectionStrings": {
"dbConn": "Server=DESKTOP-5B67SHH;
Database=TicketBooking;Trusted_Connection=True;
MultipleActiveResultSets=true"
}

In startup file, we added our service in ConfigureService method to enable the database connectivity through connection string.

public void ConfigureServices(IServiceCollection services)
{ 
    //Add database services.
    var connectionString = this.Configuration.GetConnectionString("dbConn");
    services.AddDbContext<TicketBookingContext>
    (options => options.UseSqlServer(connectionString));

    // Add framework services.
    services.AddMvc();
}
var connectionString = this.Configuration.GetConnectionString("dbConn");

Here, GetConnectionString is an extension method that is passing the connection name “dbConn”.

bower.json

Bower is a Package manager that automatically adds/updates client side packages (like bootstrap, jquery, etc.) while we add/remove listed packages in json file.

{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.6",
    "jquery": "2.2.0",
    "jquery-validation": "1.14.0",
    "jquery-validation-unobtrusive": "3.2.6"
  }
}

Here is the listed Client-side dependencies, there is another type of dependency called Server-side dependencies. Here private: true means it will refuse to publish, prevent accidental publication of private repositories.

To change bower installation location, open .bowerrc and change the directory value.

{
  "directory": "wwwroot/lib"
}

Here, you can see the dependencies have installed in wwwroot/lib folder as initial value.

bundleconfig.json

Bundling and minifying JavaScript, CSS and HTML files in any project. Download BundlerMinifierVsix & install in Visual Studio 2015. Restart the IDE.

Task Runner Explorer will appear, to update all, right click > Update all files > Run.

Finally, the output file will be generated.

Here is how a bundleconfig.json looks like:

// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

program.cs

This is the main point of any ASP.NET core application that prepares the host to run all configured services. Here is the program.cs code snippet.

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

In program.cs class, simply do the job of configuring & launching a host using WebHostBuilder. As we know, .NET Core application is a Console Application that needs to execute by host. WebHostBuilder is creating the host to bootstrap the server by UseKestrel() extension method, this means Kestrel server is going to host the application. There is another extension method UseIISIntegration() that is for IIS Server. Here's a diagram that clarifies the process between IIS and ASP.NET Core applications.

Source: ASP.NET Core Module overview By Tom Dykstra, Rick Strahl, and Chris Ross

The WebHostBuilder is responsible for creating the host that will bootstrap the server for the app. learn more about hosting… We can say that .NET Core Application needs a host to launch that defines which server is going to use, where to get the content files and specify the startup (middleware) services.

project.json

The project.json file stores the application information, dependencies, and compiler settings. It has several sections like Dependencies, Tools, Frameworks, Build Options and much more. Here, I have shown how the default project.json content looks like:

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis 
            --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Let’s explorer the different sections in it step by step:

project.json > Dependencies

This section manages the project dependencies using key/value pair, we can add new dependencies if required, intellisense will help up to include with name & version.

As you can see from the upper image, I was adding three new packages for database service, intellisense was helping me by showing the version of that package. While I saved the changes, it automatically restored the required dependencies from NuGet.

project.json > Tools: This section manages & lists command line tools, we can see IISIntegration. Tools is added by default which is a tool that contains dotnet publish IIS command for publishing the application on IIS.

"tools": {
  "BundlerMinifier.Core": "2.0.238",
  "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
  "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
  "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
}

EntityFrameworkCore Tools (Command line tool for EF Core) Includes Commands

For Package Manager Console:

  • Scaffold-DbContext
  • Add-Migration
  • Update-Database

For Command Window

  • dotnet ef dbcontext scaffold

Both EF commands are show here, please take a close look at them. If we disable the EntityFrameworkCore Tools and run the command, it will show the below error in Package Manager Console:

project.json > Frameworks

Define the framework that is supported in this application, we can use multiple frameworks by configuring in this section.

"frameworks": {
  "netcoreapp1.0": {
    "dependencies": {
    },
    "imports": [
      "dotnet5.6",
      "portable-net45+win8"
    ]
  }
}

Let’s clarify a bit more, in the framework section, we are targeting netcoreapp1.0 framework. By configuring import section, we can use several targeted packages/class libraries that are different from our application target version. Here "dotnet5.6" for older .NET Core preview versions, and "portable-net45+win8" for portable class library (PCL) profiles, that known as Target Framework Monikers (TFMs). We can use multiple frameworks by adding "net461": {} in the framework section.

"frameworks": {
  "net461": {
    "dependencies": {

    }
  },
  "netcoreapp1.0": {
    "dependencies": {
      "Microsoft.NETCore.App": {
        "version": "1.0.1",
        "type": "platform"
      }
    },
    "imports": [
      "dotnet5.6",
      "portable-net45+win8"
    ]
  }
}

You may notice that we have to move our Microsoft.NETCore.App dependency from global dependencies to specific framework dependency section.

This is how we are using multiple frameworks/runtimes that support.

project.json > Build Options

Options that are passed to compiler while build application.

"buildOptions": {
  "emitEntryPoint": true,
  "preserveCompilationContext": true
}

project.json > RuntimeOptions

Manage server garbage collection at application runtime.

"runtimeOptions": {
  "configProperties": {
    "System.GC.Server": true
  }
}

project.json > PublishOptions

This defines the file/folder to include/exclude to/from the output folder while publishing the application.

"publishOptions": {
  "include": [
    "wwwroot",
    "**/*.cshtml",
    "appsettings.json",
    "web.config"
  ]
}

project.json > Scripts

Scripts is an object type which specifies which scripts to run during build or while publishing the application.

"scripts": {
  "prepublish": [ "bower install", "dotnet bundle" ],
  "postpublish": [ "dotnet publish-iis 
                    --publish-folder %publish:OutputPath% 
                    --framework %publish:FullTargetFramework%" ]
}

Learn more about project.json file...

startup.cs

This is the entry point of every ASP.NET Core application, provides services that application requires. Here’s a diagram that shows what happens at runtime when it is run for the first time.

In Startup class, there are several methods with different responsibilities. Here, I have separated them, the very first is the constructor of Startup class. In the constructor, IHostingEnvironment instance is passed as parameter to get the web hosting environment details.

public Startup(IHostingEnvironment env)
{
   var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", 
                optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
                optional: true)
                .AddEnvironmentVariables();
       Configuration = builder.Build();
} 

The instance of ConfigurationBuilder calls the extension methods of multiple configuration source, then chain calls together by order as a fluent API.

public IConfigurationRoot Configuration { get; } The IConfigurationRoot forces the configuration values to be reloaded while application is running & configuration data is changed. Next method is ConfigureServices that gets called before Configure method. In this section, we can configure our required service to use at runtime in our application. Instance of IServiceCollection has passed as parameter. IServiceCollection specifies collection of different services.

public void ConfigureServices(IServiceCollection services)
{
    //Add framework services.
    services.AddMvc();

    //Add database services.
    var connectionString = 
    this.Configuration.GetConnectionString("dbConn");
    services.AddDbContext<TicketBookingContext>
    (options => options.UseSqlServer(connectionString));
}

In Startup class, the Configure() method handles the HTTP request .

public void Configure(IApplicationBuilder app, 
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
}

The full startup looks like this:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", 
            optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
            optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // 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();
    }

    // This method gets called by the runtime. 
    // Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, 
    IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

web.config

In ASP.NET Core, the application configuration is now stored in appsettings.json file. Previously, this was stored in web.config file. Here is how the default web.config file looks like:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <!--
    Configure your application settings in appsettings.json. 
    Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
  -->

  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" 
      verb="*" modules="AspNetCoreModule" 
      resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" 
    arguments="%LAUNCHER_ARGS%" 
    stdoutLogEnabled="false" 
    stdoutLogFile=".\logs\stdout" 
    forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>

Web.config is used only for configuration while hosting is done in IIS. In handler section, this is where IIS handles a request by passing it to ASP.NET Core Module.

<handlers>
  <add name="aspNetCore" path="*" 
  verb="*" modules="AspNetCoreModule" 
  resourceType="Unspecified" />
</handlers>

We can specify environment through web.config in IIS.

<aspNetCore processPath="dotnet" 
arguments=".\CoreMVC.dll" stdoutLogEnabled="false" 
stdoutLogFile=".\logs\stdout" 
forwardWindowsAuthToken="false">
   <environmentVariables>
     <environmentVariable name="ASPNETCORE_ENVIRONMENT" 
     value="Development" />
   </environmentVariables>
</aspNetCore>

Working with Data Using ASP.Net Core MVC (CRUD)

Database Creation

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

USE [TicketBooking]
GO

/****** Object:  Table [dbo].[Ticket]    Script Date: 11/22/2016 1:25:55 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Ticket](
	[TicketID] [int] NOT NULL,
	[DestinationFrom] [nvarchar](50) NULL,
	[DestinationTo] [nvarchar](50) NULL,
	[TicketDate] [datetime] NULL,
	[TicketFee] [numeric](18, 2) NULL,
 CONSTRAINT [PK_Ticket] PRIMARY KEY CLUSTERED 
(
	[TicketID] 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

Reverse Engineer

Add Dependency Packages:

"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools":"1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1"

Add Tools:

"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

Packages will automatically be restored by IDE.

Create the EF model from the existing database.

  1. Tools –> NuGet Package Manager –> Package Manager Console
  2. Run the following command:
Scaffold-DbContext "Server=DESKTOP-5B67SHH;
Database=TicketBooking;Trusted_Connection=True;" 
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

As you can see, models has created in Models folder. Rewrite Entity from Database with below Command if database has any changes.

Scaffold-DbContext "Server=DESKTOP-5B67SHH;
Database=TicketBooking;Trusted_Connection=True;" 
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force

Context

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace CoreMVC.Models
{
    public partial class TicketBookingContext : DbContext
    {
        public TicketBookingContext
        (DbContextOptions<TicketBookingContext> options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Ticket>(entity =>
            {
                entity.Property(e => e.TicketId).HasColumnName("TicketID");

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

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

                entity.Property(e => e.TicketDate).HasColumnType("datetime");

                entity.Property(e => e.TicketFee).HasColumnType("numeric");

                entity.Property(e => e.Vat)
                    .HasColumnName("VAT")
                    .HasColumnType("numeric");
            });
        }

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

MVC Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreMVC.Models;
using Microsoft.EntityFrameworkCore;

// For more information on enabling MVC for empty projects, 
// visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace CoreMVC.Controllers
{
    public class TicketsController : Controller
    {
        private TicketBookingContext _ctx = null;
        public TicketsController(TicketBookingContext context)
        {
            _ctx = context;
        }

        // GET: Tickets/Index/
        public async Task<IActionResult> Index()
        {
            List<Ticket> tickets = null;
            try
            {
                tickets = await _ctx.Ticket.ToListAsync();

            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return View(tickets);
        }

        // GET: Tickets/Create
        public IActionResult Create()
        {
            return View();
        }

        [ValidateAntiForgeryToken, HttpPost]
        public async Task<IActionResult> Create(Ticket ticket)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _ctx.Add(ticket);
                    await _ctx.SaveChangesAsync();
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
            return View(ticket);
        }

        // GET: Tickets/Details/5 
        public async Task<IActionResult> Details(int? id)
        {
            object ticket = null;
            try
            {
                if ((id != null) && (id > 0))
                {
                    ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return View(ticket);
        }

        // GET: Tickets/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            object ticket = null;
            try
            {
                if ((id != null) && (id > 0))
                {
                    ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return View(ticket);
        }

        [ValidateAntiForgeryToken, HttpPost]
        public async Task<IActionResult> Edit(int id, Ticket ticket)
        {
            if (id == ticket.TicketId)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        _ctx.Update(ticket);
                        await _ctx.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException dce)
                    {
                        if (!TicketExists(ticket.TicketId))
                        {
                            return NotFound();
                        }
                        else
                        {
                            dce.ToString();
                        }
                    }
                    return RedirectToAction("Index");
                }
            }

            return View(ticket);
        }

        // GET: Tickets/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            object ticket = null;

            try
            {
                if ((id != null) && (id > 0))
                {
                    ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                    if (ticket == null)
                    {
                        return NotFound();
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return View(ticket);
        }

        // POST: Tickets/Delete/5
        [ValidateAntiForgeryToken, HttpPost, ActionName("Delete")]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            try
            {
                var ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                _ctx.Ticket.Remove(ticket);
                await _ctx.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return RedirectToAction("Index");
        }

        private bool TicketExists(int id)
        {
            return _ctx.Ticket.Any(e => e.TicketId == id);
        }
    }
}

WebAPI Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreMVC.Models;
using Microsoft.EntityFrameworkCore;

// For more information on enabling Web API for empty projects, 
// visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace CoreMVC.Controllers
{
    [Route("api/[controller]")]
    public class TicketController : Controller
    {
        private TicketBookingContext _ctx = null;
        public TicketController(TicketBookingContext context)
        {
            _ctx = context;
        }

        // GET: api/Ticket/GetTicket
        [HttpGet("GetTicket"), Produces("application/json")]
        public async Task<object> GetTicket()
        {
            List<Ticket> Tickets = null;
            object result = null;
            try
            {
                using (_ctx)
                {
                    Tickets = await _ctx.Ticket.ToListAsync();
                    result = new
                    {
                        Tickets
                    };
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return Tickets;
        }

        // GET api/Ticket/GetTicketByID/5
        [HttpGet("GetTicketByID/{id}"), 
        Produces("application/json")]
        public async Task<Ticket> GetTicketByID(int id)
        {
            Ticket contact = null;
            try
            {
                using (_ctx)
                {
                    contact = await _ctx.Ticket.FirstOrDefaultAsync
                    (x => x.TicketId == id);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return contact;
        }

        // POST api/Ticket/PostTicket
        [HttpPost, Route("PostTicket"), 
        Produces("application/json")]
        public async Task<object> PostTicket([FromBody]Ticket model)
        {
            object result = null; string message = "";
            if (model == null)
            {
                return BadRequest();
            }
            using (_ctx)
            {
                using (var _ctxTransaction = _ctx.Database.BeginTransaction())
                {
                    try
                    {
                        _ctx.Ticket.Add(model);
                        await _ctx.SaveChangesAsync();
                        _ctxTransaction.Commit();
                        message = "Saved Successfully";
                    }
                    catch (Exception e)
                    {
                        _ctxTransaction.Rollback();
                        e.ToString();
                        message = "Saved Error";
                    }

                    result = new
                    {
                        message
                    };
                }
            }
            return result;
        }

        // PUT api/Ticket/PutTicket/5
        [HttpPut, Route("PutTicket/{id}")]
        public async Task<object> 
        PutContact(int id, [FromBody]Ticket model)
        {
            object result = null; string message = "";
            if (model == null)
            {
                return BadRequest();
            }
            using (_ctx)
            {
                using (var _ctxTransaction = _ctx.Database.BeginTransaction())
                {
                    try
                    {
                        var entityUpdate = _ctx.Ticket.FirstOrDefault
                        (x => x.TicketId == id);
                        if (entityUpdate != null)
                        {
                            entityUpdate.DestinationFrom = model.DestinationFrom;
                            entityUpdate.DestinationTo = model.DestinationTo;
                            entityUpdate.TicketFee = model.TicketFee;

                            await _ctx.SaveChangesAsync();
                        }
                        _ctxTransaction.Commit();
                        message = "Entry Updated";
                    }
                    catch (Exception e)
                    {
                        _ctxTransaction.Rollback(); e.ToString();
                        message = "Entry Update Failed!!";
                    }

                    result = new
                    {
                        message
                    };
                }
            }
            return result;
        }

        // DELETE api/Ticket/DeleteTicketByID/5
        [HttpDelete, Route("DeleteTicketByID/{id}")]
        public async Task<object> DeleteContactByID(int id)
        {
            object result = null; string message = "";
            using (_ctx)
            {
                using (var _ctxTransaction = _ctx.Database.BeginTransaction())
                {
                    try
                    {
                        var idToRemove = _ctx.Ticket.SingleOrDefault(x => x.TicketId == id);
                        if (idToRemove != null)
                        {
                            _ctx.Ticket.Remove(idToRemove);
                            await _ctx.SaveChangesAsync();
                        }
                        _ctxTransaction.Commit();
                        message = "Deleted Successfully";
                    }
                    catch (Exception e)
                    {
                        _ctxTransaction.Rollback(); e.ToString();
                        message = "Error on Deleting!!";
                    }

                    result = new
                    {
                        message
                    };
                }
            }
            return result;
        }
    }
}

Output

Hope this will help!

References

  1. https://en.wikipedia.org/wiki/.NET_Framework
  2. https://en.wikipedia.org/wiki/.NET_Framework_version_history
  3. https://dotnet.github.io
  4. https://docs.microsoft.com/en-us/aspnet/core
  5. https://github.com/aspnet
  6. https://www.microsoft.com/net/core/platform
  7. https://github.com/dotnet/core
  8. https://docs.microsoft.com/en-us/dotnet/articles/core/index
  9. http://www.codeproject.com/Articles/1115771/NET-CORE-MVC-ANGULARJS-STARTUP
  10. http://www.codeproject.com/Articles/1118189/CRUD-USING-NET-CORE-ANGULARJS-WEBAPI
  11. https://docs.microsoft.com/en-us/aspnet/core

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Shashangka Shekhar
Software Developer (Senior) Amber Group
Bangladesh Bangladesh
Hi, I am Shashangka Shekhar,

Working with Microsoft Technologies. Since March 2011, it was my first step to working with Microsoft Technologies, achieved bachelor’s degree on Computer Science from State University of Bangladesh(Dhaka). Have 5+ years of professional experience, currently working as Senior Software Engineer at Amber Group(MIS).

I believe in desire of learning & also love to be a part of .Net Community by sharing knowledge’s.

You may also be interested in...

Comments and Discussions

 
QuestionThank you Pin
AshtonAsh1-Dec-16 1:25
memberAshtonAsh1-Dec-16 1:25 
AnswerRe: Thank you Pin
Shashangka Shekhar1-Dec-16 1:47
memberShashangka Shekhar1-Dec-16 1:47 
GeneralMy vote of 5 Pin
Shamim Uddin29-Nov-16 5:55
professionalShamim Uddin29-Nov-16 5:55 
GeneralRe: My vote of 5 Pin
Shashangka Shekhar29-Nov-16 5:57
memberShashangka Shekhar29-Nov-16 5:57 
QuestionAll images are missing Pin
Aless Alessio29-Nov-16 0:18
memberAless Alessio29-Nov-16 0:18 
AnswerRe: All images are missing Pin
Shashangka Shekhar29-Nov-16 0:27
memberShashangka Shekhar29-Nov-16 0:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 29 Nov 2016
Article Copyright 2016 by Shashangka Shekhar
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid