<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: EzzyLearning.net</title>
    <description>The latest articles on DEV Community by EzzyLearning.net (@ezzylearning).</description>
    <link>https://dev.to/ezzylearning</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F688346%2Fc1b49c44-a7f5-4939-be16-b04111dce149.png</url>
      <title>DEV Community: EzzyLearning.net</title>
      <link>https://dev.to/ezzylearning</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ezzylearning"/>
    <language>en</language>
    <item>
      <title>Display Live Sports Updates using ASP.NET Core SignalR</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Thu, 21 Oct 2021 16:54:47 +0000</pubDate>
      <link>https://dev.to/ezzylearning/display-live-sports-updates-using-aspnet-core-signalr-4i14</link>
      <guid>https://dev.to/ezzylearning/display-live-sports-updates-using-aspnet-core-signalr-4i14</guid>
      <description>&lt;p&gt;Innovations like Google Live Search and real-time updates from social media apps e.g. Facebook or Twitter have changed the user’s expectations from the traditional apps to real-time apps. People want to see everything happening live and real-time updates to the web and mobile apps become the norm now. There are many technologies that facilitate this real-time communication between the server and the client and for .NET developers, the most popular choice is to use ASP.NET Core SignalR. Surprisingly, most of the online articles use the chat or messaging app example and I was so fed up seeing those same examples everywhere so I decided to write an article with a more interesting and real-world example related to live sports updates. In this tutorial, I will build a live football match centre application where users will be able to see the football match scores updated in real-time as soon as any particular football team will score a goal. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/SignalRLiveSportsDashboardDemo" rel="noopener noreferrer"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" alt="Display Live Sports Updates using ASP.NET Core Signal"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Real-Time Application (RTA)?
&lt;/h2&gt;

&lt;p&gt;A real-time application is a type of application that performs time-critical operations. Application has to perform certain functions within a time frame (usually seconds or milliseconds) so that users sense them as immediate or current. In the past, the developers used techniques such as HTTP Long Pooling, Server Side Events (SSE) to implement real-time applications and each one of these techniques had its pros and cons. The modern way of developing a real-time communication system is to use the protocol called Web Sockets that enables two-way communication between the server and the clients for sending and receiving messages and is widely supported by all modern browsers.&lt;/p&gt;

&lt;p&gt;Following are some of the common examples of real-time applications&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Videoconference Apps&lt;/li&gt;
&lt;li&gt;VoIP Apps&lt;/li&gt;
&lt;li&gt;Online Gaming Apps&lt;/li&gt;
&lt;li&gt;Chatting or Instant Messaging Apps&lt;/li&gt;
&lt;li&gt;Collaboration Apps&lt;/li&gt;
&lt;li&gt;Social Media Apps&lt;/li&gt;
&lt;li&gt;GPS Tracking Apps&lt;/li&gt;
&lt;li&gt;Voting Apps&lt;/li&gt;
&lt;li&gt;Auction Apps&lt;/li&gt;
&lt;li&gt;Alerts or Notification Apps&lt;/li&gt;
&lt;li&gt;Dashboards and Monitoring Apps&lt;/li&gt;
&lt;li&gt;Stock Ticker Apps&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Overview of ASP.NET Core SignalR?
&lt;/h2&gt;

&lt;p&gt;ASP.NET Core SignalR is an open-source library for adding real-time functionality in ASP.NET web applications. It allows us to send server-side push notifications and contents to the client instantly. It provides an API to facilitate server-to-client remote procedure calls (RPC) and using this API, we can call JavaScript functions on clients from the server-side .NET code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhxmddvexeewhiqbribo8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhxmddvexeewhiqbribo8.png" alt="ASP.NET Core SignalR"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Following are some of the common features of ASP.NET Core SignalR.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Handles connection management automatically&lt;/li&gt;
&lt;li&gt;Sends messages to all connected clients simultaneously. For example, live match updates&lt;/li&gt;
&lt;li&gt;Sends messages to specific clients or groups. For example, a specific chat room or a specific user&lt;/li&gt;
&lt;li&gt;Scales to handle increasing traffic&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To handle real-time communication in a wide range of browsers and devices, SignalR supports the following transport methods and it automatically chooses the best transport method that is within the capabilities of the server and client.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;WebSockets&lt;/li&gt;
&lt;li&gt;Server-Sent Events&lt;/li&gt;
&lt;li&gt;Long Polling&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffspobhavahxewe9fdx18.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffspobhavahxewe9fdx18.png" alt="Web Sockets enables two-way communication between the server and the clients"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;SignalR for ASP.NET Core supports any server platform that ASP.NET Core supports and the following table shows the browser support for SignalR.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Browser&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Version&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Apple Safari, including iOS&lt;/td&gt;
&lt;td&gt;Latest Version&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Google Chrome, including Android&lt;/td&gt;
&lt;td&gt;Latest Version&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Microsoft Edge&lt;/td&gt;
&lt;td&gt;Latest Version&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Mozilla Firefox&lt;/td&gt;
&lt;td&gt;Latest Version&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  What is a SignalR Hub?
&lt;/h2&gt;

&lt;p&gt;The SignalR Hub is a high-level API that enables us to call methods on connected clients from the server. In the server code, we define methods that are called by the client. In the client code, we define methods that are called from the server. SignalR takes care of everything behind the scenes that makes real-time client-to-server and server-to-client communications possible.&lt;/p&gt;

&lt;p&gt;Hubs call client-side code by sending messages that contain the name and parameters of the client-side method. Objects sent as method parameters are deserialized using the configured protocol. The client tries to match the name to a method in the client-side code. When the client finds a match, it calls the method and passes to it the deserialized parameter data.&lt;/p&gt;

&lt;p&gt;To create a hub in your code, you need to create a class that inherits from the &lt;strong&gt;Hub&lt;/strong&gt; class and then you can create public methods in the Hub. These public methods can be called from connected clients. In the example below when any connected client will call the &lt;strong&gt;SendMessage&lt;/strong&gt; method then the method will broadcast the &lt;strong&gt;user&lt;/strong&gt; and &lt;strong&gt;message&lt;/strong&gt; parameters values to all the clients connected to this Hub.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ChatHub : Hub
{
    public Task SendMessage(string user, string message)
    {
        return Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we don’t want to broadcast messages to all connected clients, then we also have other options. The following table shows the available methods.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;All&lt;/td&gt;
&lt;td&gt;Calls a method on all connected clients&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Caller&lt;/td&gt;
&lt;td&gt;Calls a method on the client that invoked the hub method&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Others&lt;/td&gt;
&lt;td&gt;Calls a method on all connected clients except the client that invoked the method&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;AllExcept&lt;/td&gt;
&lt;td&gt;Calls a method on all connected clients except for the specified connections&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Client&lt;/td&gt;
&lt;td&gt;Calls a method on a specific connected client&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Clients&lt;/td&gt;
&lt;td&gt;Calls a method on specific connected clients&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Group&lt;/td&gt;
&lt;td&gt;Calls a method on all connections in the specified group&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;GroupExcept&lt;/td&gt;
&lt;td&gt;Calls a method on all connections in the specified group, except the specified connections&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Groups&lt;/td&gt;
&lt;td&gt;Calls a method on multiple groups of connections&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;OthersInGroup&lt;/td&gt;
&lt;td&gt;Calls a method on a group of connections, excluding the client that invoked the hub method&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;User&lt;/td&gt;
&lt;td&gt;Calls a method on all connections associated with a specific user&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Users&lt;/td&gt;
&lt;td&gt;Calls a method on all connections associated with the specified users&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Overview of Football Match Centre Application
&lt;/h2&gt;

&lt;p&gt;I covered some of the basic concepts of ASP.NET Core SignalR. It is now time to build a real-world application that will cover everything we have learned so far. The application will consist of the following two pages&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Admin Page&lt;/strong&gt; – This page will display the list of football matches and will allow the admin to update football match scores. Whenever any team will score a goal, an admin will click the &lt;strong&gt;Add Goal&lt;/strong&gt; button to add one goal for any particular team.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3edkr8ytl2d8rih7j2rm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3edkr8ytl2d8rih7j2rm.png" alt="SignalR - Admin Page with Updated Goals"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Match Centre Page&lt;/strong&gt; – This page will display the list of matches to all live users. Every time, an admin will add a goal to any team from the admin page, the match results will update for all online users in real-time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn0pfpa1nezw2wjy9zjfj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn0pfpa1nezw2wjy9zjfj.png" alt="SignalR - Match Center Live Page"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Create Database and EF Core DBContext
&lt;/h2&gt;

&lt;p&gt;Before we start building the application, I created a database named &lt;strong&gt;FootballDb&lt;/strong&gt; in SQL Server 2016 and the database has the following two tables.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw9w73mrnes0p2znagaej.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw9w73mrnes0p2znagaej.png" alt="Database Schema for Football Match Center SignalR Application"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Teams&lt;/strong&gt; table will store minimum team information and the &lt;strong&gt;Matches&lt;/strong&gt; table will store the information about the matches scheduled to be played between two Teams. Both &lt;strong&gt;Team1&lt;/strong&gt; and &lt;strong&gt;Team2&lt;/strong&gt; columns in the Matches table will be foreign keys and they will store the primary key value from the Teams table. I also added the following information about some English Premier League football teams and matches.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpcfyi7esi6ascgjd4b4o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpcfyi7esi6ascgjd4b4o.png" alt="Teams and Matches Data in Database for SignalR Application"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s start by creating an ASP.NET Core MVC Web Application in Visual Studio 2019. We need to connect the database to display match information and for this tutorial, I will use Entity Framework Core (Database First) approach. If you don’t know how to use Entity Framework Core, then you can read my post &lt;a href="https://www.ezzylearning.net/tutorial/data-access-in-asp-net-core-using-ef-core-database-first" rel="noopener noreferrer"&gt;Data Access in ASP.NET Core using EF Core (Database First)&lt;/a&gt;. We need to install the following packages to use Entity Framework Core in our application so add these packages using the NuGet package manager.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Design" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.Design&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/" rel="noopener noreferrer"&gt;Microsoft.EntityFramewo&lt;/a&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/" rel="noopener noreferrer"&gt;r&lt;/a&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/" rel="noopener noreferrer"&gt;kCore.Tools&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Add the following connection string in appsettings.json file and don’t forget to replace the &lt;strong&gt;DB_SERVER&lt;/strong&gt; with your database server name in the connection added in asppsettings.json file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "ConnectionStrings": {
    "DefaultConnection": "Server=DB_SERVER; Database=FootballDb; Trusted_Connection=True; MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, add a &lt;strong&gt;Data&lt;/strong&gt; folder in the project and run the following command in &lt;strong&gt;Package Manager Console&lt;/strong&gt; to generate the entity models and the DbContext class with the name &lt;strong&gt;FootballDbContext&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Scaffold-DbContext -Connection "Server=DB_SERVER; Database=FootballDb; Trusted_Connection=True; MultipleActiveResultSets=true;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir "Models" -ContextDir "Data" -Context "FootballDbContext" -NoOnConfiguring
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Final step is to configure the Entity Framework provider for SQL Server in the &lt;strong&gt;ConfigureService&lt;/strong&gt; method of the &lt;strong&gt;Startup.cs&lt;/strong&gt; file as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.AddDbContext&amp;lt;FootballDbContext&amp;gt;(options =&amp;gt; options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implement Application Services and Web APIs
&lt;/h2&gt;

&lt;p&gt;Our application will call Web APIs from both admin and match centre pages and those Web APIs will call the backend application services to communicate with the database. Create a &lt;strong&gt;Services&lt;/strong&gt; folder in the project and create the following &lt;strong&gt;IFootballService&lt;/strong&gt; interface.&lt;/p&gt;

&lt;h4&gt;
  
  
  IFootballService.cs
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IFootballService
{
    Task&amp;lt;IEnumerable&amp;lt;MatchViewModel&amp;gt;&amp;gt; GetMatchesAsync();
    Task UpdateMatchAsync(MatchUpdateModel model);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our application only needs two methods to perform its operations.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;GetMatchesAsync&lt;/strong&gt; method will return the list of matches to be displayed on both pages&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;UpdateMatchAsync&lt;/strong&gt; method will update the match information in the database whenever the admin will click the “Add Goal” button on the admin page. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Both of the methods above are using two View Model classes and you can declare these classes in the &lt;strong&gt;Models&lt;/strong&gt; folder. Here is the definition of MatchViewModel class.&lt;/p&gt;

&lt;h4&gt;
  
  
  MatchViewModel.cs
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MatchViewModel
{
    public int Id { get; set; }
    public DateTime? Date { get; set; }

    public int Team1Id { get; set; }
    public int Team2Id { get; set; }

    public string Team1Name { get; set; }
    public string Team2Name { get; set; }

    public string Team1Logo { get; set; }
    public string Team2Logo { get; set; }

    public int? Team1Goals { get; set; }
    public int? Team2Goals { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Following is the definition of MatchUpdateModel class&lt;/p&gt;

&lt;h4&gt;
  
  
  MatchUpdateModel.cs
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MatchUpdateModel
{
    public int? MatchId { get; set; }
    public int? TeamId { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create the following &lt;strong&gt;FootballService&lt;/strong&gt; class in the Services folder and implement the &lt;strong&gt;IFootballService&lt;/strong&gt; interface on the class. We need to define both methods declared in the &lt;strong&gt;IFootballService&lt;/strong&gt; interface. Notice, how the &lt;strong&gt;FootballDbContext&lt;/strong&gt; is injected into the service constructor to make sure we can connect the &lt;strong&gt;FootballDb&lt;/strong&gt; database and perform database operations.&lt;/p&gt;

&lt;h4&gt;
  
  
  FootballService.cs
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FootballService : IFootballService
{
    private readonly FootballDbContext _context;

    public FootballService(FootballDbContext context)
    {
        _context = context;
    }

    public async Task&amp;lt;IEnumerable&amp;lt;MatchViewModel&amp;gt;&amp;gt; GetMatchesAsync()
    {
        var query = from m in _context.Matches
            join t1 in _context.Teams on m.Team1 equals t1.Id
            join t2 in _context.Teams on m.Team2 equals t2.Id
            select new MatchViewModel()
            {
                Id = m.Id,
                Team1Id = t1.Id,
                Team2Id = t2.Id,
                Team1Name = t1.Name,
                Team2Name = t2.Name,
                Team1Logo = t1.Logo,
                Team2Logo = t2.Logo,
                Team1Goals = m.Team1Goals ?? 0,
                Team2Goals = m.Team2Goals ?? 0
            };
        return await query.ToListAsync();
    }

    public async Task UpdateMatchAsync(MatchUpdateModel model)
    {
        var match = _context.Matches.FirstOrDefault(x =&amp;gt; x.Id == model.MatchId);
        if (match != null)
        {
            if (model.TeamId == match.Team1)
            {
                match.Team1Goals = (match.Team1Goals ?? 0) + 1;
            }

            if (model.TeamId == match.Team2)
            {
                match.Team2Goals = (match.Team2Goals ?? 0) + 1;
            }

            _context.Matches.Update(match);
            await _context.SaveChangesAsync(); 
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;GetMatchesAsync&lt;/strong&gt; method is using LINQ to join both Teams and Matches table using the Team1 and Team2 foreign keys and then returns the list of &lt;strong&gt;MatchViewModel&lt;/strong&gt; class objects. The &lt;strong&gt;UpdateMatchAsync&lt;/strong&gt; method will first query particular match information from the database and then it will add 1 goal in either Team1 or Team2 depending upon the TeamId value passed to it from the front end. If the admin will add a goal in Team 1 then the Team1 goals will be incremented by 1 and if the admin will add a goal in Team 2 then the Team 2 goals will increment by 1.&lt;/p&gt;

&lt;p&gt;To inject and use the above &lt;strong&gt;FootballService&lt;/strong&gt; in controllers, we need to register it with ASP.NET Core dependency injection container and you can do this by adding the following line in the &lt;strong&gt;ConfigureService&lt;/strong&gt; method of the &lt;strong&gt;Startup.cs&lt;/strong&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.AddScoped&amp;lt;IFootballService, FootballService&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To create the Web API, add the following &lt;strong&gt;MatchController&lt;/strong&gt; class in the &lt;strong&gt;Controllers&lt;/strong&gt; folder. The class inherits from the &lt;strong&gt;ControllerBase&lt;/strong&gt; class and the &lt;strong&gt;IFootballService&lt;/strong&gt; interface is injected in the class using the constructor. The methods of the class are pretty straightforward as they are simply calling the corresponding methods we defined in the &lt;strong&gt;FootballService&lt;/strong&gt; above.&lt;/p&gt;

&lt;h4&gt;
  
  
  MatchController.cs
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ApiController]
public class MatchController : ControllerBase
{
    private readonly IFootballService _footballService;  

    public MatchController(IFootballService footballService)
    {
        _footballService = footballService; 
    }

    // GET: api/Matches
    [HttpGet]
    [Route("api/Matches")]
    public async Task&amp;lt;IEnumerable&amp;lt;MatchViewModel&amp;gt;&amp;gt; GetMatchesAsync()
    {
        return await _footballService.GetMatchesAsync();
    }

    // PUT: api/Matches
    [HttpPut]
    [Route("api/Matches")]
    public async Task UpdateMatchAsync(MatchUpdateModel model)
    {
        await _footballService.UpdateMatchAsync(model); 
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are defining the API URLs using the &lt;strong&gt;[Route]&lt;/strong&gt; attribute so we have to add &lt;strong&gt;MapControllers&lt;/strong&gt; method call in &lt;strong&gt;Startup.cs&lt;/strong&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.UseEndpoints(endpoints =&amp;gt;
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapControllers(); 
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To make sure everything is working as expected, run the project by pressing F5 and open the following URL in the browser address bar. Please note that the port number shown in the following URL can be different in your case.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:58316/api/Matches" rel="noopener noreferrer"&gt;http://localhost:58316/api/Matches&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You should be able to see the matches information returned from the Web API in JSON format&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zyu7cvdx344itoasf32.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zyu7cvdx344itoasf32.png" alt="Match Web API returning list of Matches"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to learn more about ASP.NET Core Web APIs then read my post &lt;a href="https://www.ezzylearning.net/tutorial/a-developers-guide-for-creating-web-apis-with-asp-net-core-5" rel="noopener noreferrer"&gt;A Developer’s Guide for Creating Web APIs with ASP.NET Core 5&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating Admin Page to Update Football Match Scores
&lt;/h2&gt;

&lt;p&gt;Once our database, services, and Web APIs are ready, it is now time to develop the Admin Page that will allow admin to update match scores. Create the following &lt;strong&gt;AdminController&lt;/strong&gt; class in the &lt;strong&gt;Controllers&lt;/strong&gt; folder and add an &lt;strong&gt;Index&lt;/strong&gt; action method in it.&lt;/p&gt;

&lt;h4&gt;
  
  
  AdminController.cs
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class AdminController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Index method will display the &lt;strong&gt;Index.cshtml&lt;/strong&gt; Razor View available in &lt;strong&gt;Views/Admin&lt;/strong&gt; folder. Open the &lt;strong&gt;Index.cshtml&lt;/strong&gt; file and add the following code to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@{
    ViewData["Title"] = "Admin Area";
}

&amp;lt;table class="table match-center"&amp;gt;
    &amp;lt;tbody id="listMatches"&amp;gt;
    &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;

@section Scripts{
    &amp;lt;script src="~/js/admin.js"&amp;gt;&amp;lt;/script&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There isn’t too much going on in the view. I declared an HTML table with an empty &lt;strong&gt;&amp;lt;tbody&amp;gt;&lt;/strong&gt; element. The important thing to note is that the &lt;strong&gt;&amp;lt;tbody&amp;gt;&lt;/strong&gt; element has been given an id &lt;strong&gt;listMatches&lt;/strong&gt;. This is because I will fetch the list of matches from the Web API using JQuery AJAX &lt;strong&gt;get&lt;/strong&gt; method and will generate the table rows dynamically. In the end, I included a JavaScript file &lt;strong&gt;admin.js&lt;/strong&gt; which we need to add next in &lt;strong&gt;wwwroot/js&lt;/strong&gt; folder.&lt;/p&gt;

&lt;h4&gt;
  
  
  admin.js
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$(document).ready(function () {
    loadMatches(); 
});

function loadMatches() {
    $.get("/api/Matches", null, function (response) {
        bindMatches(response);
    });
}

function bindMatches(matches) {
    var html = "";
    $("#listMatches").html("");
    $.each(matches,
        function(index, match) {
            html += "&amp;lt;tr data-match-id='" + match.id + "'&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;img class='team-logo' src='/images/" + match.team1Logo + "'/&amp;gt;";
            html += "&amp;lt;span class='team-name'&amp;gt;" + match.team1Name + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;span data-team-id='" + match.team1Id + "' class='team-goals'&amp;gt;" + match.team1Goals + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;input type='button' class='btn btn-success' value='Add Goal' data-match-id='" + match.id + "' data-team-id='" + match.team1Id + "' onclick='addGoal(this);' /&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;span class='team-separator'&amp;gt; — &amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;span data-team-id='" + match.team2Id + "' class='team-goals'&amp;gt;" + match.team2Goals + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;input type='button' class='btn btn-success' value='Add Goal' data-match-id='" + match.id + "' data-team-id='" + match.team2Id + "' onclick='addGoal(this);' /&amp;gt;";

            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;img class='team-logo' src='/images/" + match.team2Logo + "'/&amp;gt;";
            html += "&amp;lt;span class='team-name'&amp;gt;" + match.team2Name + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;/tr&amp;gt;";
        });
    $("#listMatches").append(html);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the admin.js file, I am calling a &lt;strong&gt;loadMatches&lt;/strong&gt; function that will make an AJAX call to our Web API endpoint &lt;strong&gt;api/Matches,&lt;/strong&gt; and once we have the API response available it will simply pass the response to &lt;strong&gt;bindMatches&lt;/strong&gt; function that will generate the HTML table rows with matches information.&lt;/p&gt;

&lt;p&gt;If you will run the project now and will navigate to &lt;strong&gt;/Admin&lt;/strong&gt; page, you will see output similar to the following.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3edkr8ytl2d8rih7j2rm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3edkr8ytl2d8rih7j2rm.png" alt="SignalR - Admin Page with Updated Goals"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note that I am loading the team logos from the &lt;strong&gt;wwwroot/images&lt;/strong&gt; folder and I have downloaded the team logos from a stock photos website. You will be able to get the logos with the article source code that I will upload to GitHub and will make available for you to download.&lt;/p&gt;

&lt;p&gt;Another important thing to notice is that all &lt;strong&gt;&lt;/strong&gt; button elements have some dynamic attributes &lt;strong&gt;data-match-id&lt;/strong&gt; and &lt;strong&gt;data-team-id&lt;/strong&gt; which are set using the match and teams Ids we are receiving in API response. Finally, we have &lt;strong&gt;onclick&lt;/strong&gt; event handler which is bind with the &lt;strong&gt;addGoal&lt;/strong&gt; function.&lt;/p&gt;

&lt;p&gt;To complete this page, we need to implement &lt;strong&gt;addGoal&lt;/strong&gt; method. This method will first get the matchId and teamId values from the &lt;strong&gt;data-match-id&lt;/strong&gt; and &lt;strong&gt;data-team-id&lt;/strong&gt; attributes we added to each &lt;strong&gt;&lt;/strong&gt; element and then it will send these parameters to &lt;strong&gt;api/Patches&lt;/strong&gt; API using the HTTP PUT method. If the AJAX call is successful, we will once again call the &lt;strong&gt;loadMatches&lt;/strong&gt; method to refresh the page&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function addGoal(element) {
    var data =
    {
        matchId: $(element).attr("data-match-id"),
        teamId: $(element).attr("data-team-id")
    }

    $.ajax({
        type: 'PUT',
        url: 'api/Matches',
        contentType: 'application/json',
        data: JSON.stringify(data)
    }).done(function() {
        loadMatches(); 
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Press F5 to run the project and try updating some matches information by adding some Goals. If you will open the database, you will also see that the goals information is also updating in the Matches table in the database. We will come back to this page later when we will add SignalR related functionality in our project. It is now time to build the Match Centre page for public users.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating Match Centre Page for Public Users
&lt;/h2&gt;

&lt;p&gt;The layout and the look and feel of our Match Centre page are almost the same as the admin page. The only difference is that the Match Centre page doesn’t have the “Add Goal” buttons available. Let’s quickly create the HomeController with the following Index action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#### HomeController.cs

public class HomeController : Controller
{ 
    public IActionResult Index()
    {
        return View();
    } 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Following is the code for &lt;strong&gt;Index.cshtml&lt;/strong&gt; view and it is also almost the same as the Index.cshtml view of AdminController we created earlier. The only difference is that it is including the &lt;strong&gt;home.js&lt;/strong&gt; file.&lt;/p&gt;

&lt;h4&gt;
  
  
  Index.cshtml
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@{
    ViewData["Title"] = "MATCH CENTER LIVE";
}

&amp;lt;table class="table match-center"&amp;gt;
    &amp;lt;tbody id="listMatches"&amp;gt;
    &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;

@section Scripts{  
    &amp;lt;script src="~/js/home.js"&amp;gt;&amp;lt;/script&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Following is the code for home.js file which is almost same as admin.js file we created earlier but this time it doesn’t have the Add Goal buttons in it.&lt;/p&gt;

&lt;h4&gt;
  
  
  home.js
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$(document).ready(function () {
    loadMatches(); 
});

function loadMatches() {
    $.get("/api/Matches", null, function (response) {
        bindMatches(response);
    });
}

function bindMatches(matches) {
    var html = "";
    $("#listMatches").html("");
    $.each(matches,
        function(index, match) {
            html += "&amp;lt;tr data-match-id='" + match.id + "'&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;img class='team-logo' src='/images/" + match.team1Logo + "'/&amp;gt;";
            html += "&amp;lt;span class='team-name'&amp;gt;" + match.team1Name + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;span data-team-id='" + match.team1Id + "' class='team-goals'&amp;gt;" + match.team1Goals + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;span class='team-separator'&amp;gt; — &amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;span data-team-id='" + match.team2Id + "' class='team-goals'&amp;gt;" + match.team2Goals + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;td&amp;gt;";
            html += "&amp;lt;img class='team-logo' src='/images/" + match.team2Logo + "'/&amp;gt;";
            html += "&amp;lt;span class='team-name'&amp;gt;" + match.team2Name + "&amp;lt;/span&amp;gt;";
            html += "&amp;lt;/td&amp;gt;";

            html += "&amp;lt;/tr&amp;gt;";
        });
    $("#listMatches").append(html);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Press F5 to run the project and you will see a page similar to the following&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F53cu3ijj0kt7pajzq35x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F53cu3ijj0kt7pajzq35x.png" alt="Match-Center-Live-Page"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Try to open both pages side by side and then click the &lt;strong&gt;Add Goal&lt;/strong&gt; button for any match and team. You will see that the Match Centre page is not updating. This is because the Match Centre page has no idea that the match information is updated in the database and it needs to fetch the updated information from the server. If you will refresh the Match Centre page, then the match scores will update. We don’t want the user to keep refreshing the page to see live match updates. We want to update the Match Centre page in real-time without any user interaction and this is where we will use SignalR that will allow us to send real-time notifications from server to client so that we can update the pages on the client instantly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" alt="Display Live Sports Updates using ASP.NET Core Signal"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started with ASP.NET Core SignalR
&lt;/h2&gt;

&lt;p&gt;SignalR supports bi-directional communication between the server and the client which means we need to have SignalR libraries at both ends. The SignalR server library is included in ASP.NET Core shared framework so we don’t need to install any package or library on the server. However, we need to install the client library and the easiest way to add the client library to our project is to use the &lt;strong&gt;LibMan&lt;/strong&gt; tool. Follow the steps below to add the SignalR client library to the project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Right-click on the project in Solution Explorer&lt;/li&gt;
&lt;li&gt;Choose &lt;strong&gt;Add &amp;gt; Client-Side&lt;/strong&gt; Library menu option.&lt;/li&gt;
&lt;li&gt;In the &lt;strong&gt;Add Client-Side Library&lt;/strong&gt; dialog, for &lt;strong&gt;Provider&lt;/strong&gt; select &lt;strong&gt;unpkg&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;For Library, enter &lt;strong&gt;@microsoft/signalr@latest&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Select &lt;strong&gt;Choose specific files&lt;/strong&gt;, expand the &lt;strong&gt;dist/browser&lt;/strong&gt; folder, and select &lt;strong&gt;signalr.js&lt;/strong&gt; and &lt;strong&gt;signalr.min.js&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Set Target Location to &lt;strong&gt;wwwroot/lib/microsoft/signalr/&lt;/strong&gt;, and select Install.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LibMan&lt;/strong&gt; will create a &lt;strong&gt;wwwroot/lib/microsoft/signalr&lt;/strong&gt; folder and will copy the selected files in it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fid0jukx1x0ouqzy0g2qu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fid0jukx1x0ouqzy0g2qu.png" alt="Download SignalR JavaScript Library using LibMan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to learn more about managing server and client libraries in ASP.NET Core projects then you can read my post &lt;a href="https://www.ezzylearning.net/tutorial/working-with-packages-and-libraries-in-asp-net-core" rel="noopener noreferrer"&gt;Working with Packages and Libraries in ASP.NET Core&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once the SignalR libraries are available, we need to create SignalR hub class. The hub class is a high-level abstraction and it handles the client-server communication. It manages connections, groups, and messaging and provides an easy-to-use API to facilitate advanced real-time scenarios. Create a &lt;strong&gt;Hubs&lt;/strong&gt; folder in the project and define the following &lt;strong&gt;MatchCentreHub&lt;/strong&gt; class inherited from the &lt;strong&gt;Hub&lt;/strong&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MatchCentreHub : Hub
{
    public async Task SendMatchCentreUpdate()
    {
        await Clients.All.SendAsync("RefreshMatchCentre");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is just one method &lt;strong&gt;SendMatchCentreUpdate&lt;/strong&gt; in MatchCentreHub class and this method can be called by a connected client to send notifications to other connected clients. I am sending notifications to &lt;strong&gt;All&lt;/strong&gt; connected clients and you can also see the client-side method name &lt;strong&gt;RefreshMatchCentre&lt;/strong&gt; mentioned as a parameter in the &lt;strong&gt;SendAsync&lt;/strong&gt; method. We will define this method in our client-side code later in this tutorial.&lt;/p&gt;

&lt;p&gt;The next step is to configure server-side SignalR and we can do this by calling the &lt;strong&gt;AddSignalR&lt;/strong&gt; method in the &lt;strong&gt;ConfigureService&lt;/strong&gt; method of the &lt;strong&gt;Startup.cs&lt;/strong&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();

    services.AddControllersWithViews();

    services.AddDbContext&amp;lt;FootballDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddScoped&amp;lt;IFootballService, FootballService&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also need to add SignalR to the routing systems so that we can expose the hub endpoint for the clients who want to connect to the hub and we can do this using the &lt;strong&gt;MapHub&lt;/strong&gt; method shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.UseEndpoints(endpoints =&amp;gt;
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapControllers();

    endpoints.MapHub&amp;lt;MatchCentreHub&amp;gt;("/matchcenterhub");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Working with SignalR JavaScript Client Library
&lt;/h2&gt;

&lt;p&gt;We need to connect Match Centre Page with the &lt;strong&gt;MatchCentreHub&lt;/strong&gt; at the server so that when the &lt;strong&gt;MatchCentreHub&lt;/strong&gt; sends notifications to Match Centre Page and call a client-side function &lt;strong&gt;RefreshMatchCentre&lt;/strong&gt; we can receive the notifications on the client and instantly refresh the Match Centre Page to give users the feeling that the page is updating in real-time.&lt;/p&gt;

&lt;p&gt;Include the SignalR JavaScript library in the &lt;strong&gt;Index.cshtml&lt;/strong&gt; page using the standard script element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@section Scripts{ 
    &amp;lt;script src="~/lib/microsoft/signalr/dist/browser/signalr.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/js/home.js"&amp;gt;&amp;lt;/script&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create the connection object in the home.js file by adding the following line at the top of the file. Notice that the connection is built with the same URL we defined at the server using the &lt;strong&gt;MapHub&lt;/strong&gt; configuration above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var connection = new signalR.HubConnectionBuilder().withUrl("/matchcenterhub").build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We want Match Centre Page to connect to server side hub as soon as the page is loaded so call the &lt;strong&gt;start&lt;/strong&gt; function as soon as the document is ready.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$(document).ready(function () {
    loadMatches();
    connection.start();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can confirm if the WebSockets connection is established successfully by refreshing the page and seeing the following lines in the browser console window.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F48l4uyl6c0zhgnmv98h6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F48l4uyl6c0zhgnmv98h6.png" alt="SignalR WebSockets connection info in browser console"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The last piece of code we need is to define the &lt;strong&gt;RefreshMatchCentre&lt;/strong&gt; function which will be called from the server whenever the server will send notifications to the client. I am just calling the &lt;strong&gt;loadMatches&lt;/strong&gt; function in &lt;strong&gt;RefreshMatchCentre&lt;/strong&gt; to refresh the matches on the page.&lt;br&gt;
&lt;br&gt;
  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection.on("RefreshMatchCentre", function (match) {
    loadMatches();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Match Centre Page is now complete and ready to receive notifications from the server and as soon as it will receive the notification, it will refresh the page and show the live match updates to the users.&lt;/p&gt;

&lt;p&gt;We need to repeat almost same steps for Admin page as well so let’s include the SignalR client library on Index.cshtml view of AdminController.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@section Scripts{
    &amp;lt;script src="~/lib/microsoft/signalr/dist/browser/signalr.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/js/admin.js"&amp;gt;&amp;lt;/script&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Build the connection object by adding the following line on top of the admin.js file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var connection = new signalR.HubConnectionBuilder().withUrl("/matchcenterhub").build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Call the start function as soon as the document is ready&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$(document).ready(function () {
    loadMatches();
    connection.start();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to write the most important line of this application. This line will invoke the method &lt;strong&gt;SendMatchCentreUpdate&lt;/strong&gt; defined in the &lt;strong&gt;MatchCentreHub&lt;/strong&gt; class available on the server. We already know that whenever any client will call the &lt;strong&gt;SendMatchCentreUpdate&lt;/strong&gt; method, the notification will be sent to all connected clients automatically. The best place to invoke the &lt;strong&gt;SendMatchCentreUpdate&lt;/strong&gt; method is when the admin updated the match by clicking the &lt;strong&gt;Add Goal&lt;/strong&gt; button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function addGoal(element) {
    var data =
    {
        matchId: $(element).attr("data-match-id"),
        teamId: $(element).attr("data-team-id")
    }

    $.ajax({
        type: 'PUT',
        url: 'api/Matches',
        contentType: 'application/json',
        data: JSON.stringify(data)
    }).done(function() {
        loadMatches();

        connection.invoke("SendMatchCentreUpdate").catch(function (err) {
            return console.error(err.toString());
        });
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is now time to see the complete application in action. Press F5 and once again open both pages side by side. Try to click the &lt;strong&gt;Add Goal&lt;/strong&gt; button on the Admin page and you will notice that the Match Centre Live Page will update in real-time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" alt="Display Live Sports Updates using ASP.NET Core Signal"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Following is the visual representation of client-server communication happening in this application using SignalR.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk8jeeyokhvy6marbvp68.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk8jeeyokhvy6marbvp68.png" alt="Live Sports Updates using ASP.NET Core SignalR"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Broadcasting from Server using ASP.NET Core SignalR
&lt;/h2&gt;

&lt;p&gt;In the above example, we were invoking the &lt;strong&gt;SendMatchCentreUpdate&lt;/strong&gt; method of &lt;strong&gt;MatchCentreHub&lt;/strong&gt; class from the client side using the SignalR client library &lt;strong&gt;invoke&lt;/strong&gt; function which we added inside &lt;strong&gt;addGoal&lt;/strong&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection.invoke("SendMatchCentreUpdate").catch(function (err) {
    return console.error(err.toString());
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sometimes, our scenario is such that we want to invoke hub methods from server-side .NET code and we want to broadcast messages and push notifications from the server to clients when some server-side event occurred. We can easily achieve this using SignalR server-side APIs. In this section of this tutorial, I will show you how you can broadcast messages from the server to clients using SignalR. Before we start, first remove all the client-side code we added in our admin page above and also remove the line where we included the &lt;strong&gt;signalr.js&lt;/strong&gt; file in our admin page.&lt;/p&gt;

&lt;p&gt;We are already calling the server-side Web API method &lt;strong&gt;UpdateMatchAsync&lt;/strong&gt; to update the goals in the database so this method is the ideal candidate to invoke the &lt;strong&gt;SendMatchCentreHub&lt;/strong&gt; method which will automatically send notifications to all connected clients.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task UpdateMatchAsync(MatchUpdateModel model)
{
    await _footballService.UpdateMatchAsync(model);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the &lt;strong&gt;MatchController&lt;/strong&gt; class declare the following object of &lt;strong&gt;IHubContext&lt;/strong&gt; type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private readonly IHubContext&amp;lt;MatchCentreHub&amp;gt; _hub;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;IHubContext&lt;/strong&gt; allows us to send messages from different areas of the application and we can inject IHubContext in controllers and services using dependency injection. Inject the IHubContext in MatchController as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public MatchController(IFootballService footballService, IHubContext&amp;lt;MatchCentreHub&amp;gt; hub)
{
    _footballService = footballService;
    _hub = hub;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we now have access to an instance of IHubContext, we can call hub methods as if we are in the hub itself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// POST: api/Matches
[HttpPut]
[Route("api/Matches")]
public async Task UpdateMatchAsync(MatchUpdateModel model)
{
    await _footballService.UpdateMatchAsync(model);

    await _hub.Clients.All.SendAsync("RefreshMatchCentre");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the application again and it should work similarly as before and the Match Centre page should update in real-time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6ancthehhglhu33wb8y.png" alt="Display Live Sports Updates using ASP.NET Core Signal"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;SignalR is one of the coolest technology available to .NET developers. Its ability to perform tasks in real-time has made this a game-changer technology. I hope in this article, you have learned how to use SignalR and you will now use it in your projects with more confidence. If you enjoyed reading this article, please share this with your friends and colleagues.&lt;/p&gt;

</description>
      <category>signalr</category>
      <category>webdev</category>
      <category>aspnetcore</category>
      <category>realtime</category>
    </item>
    <item>
      <title>A Guide for Building Angular SPA with ASP.NET Core 5 Web API</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Wed, 20 Oct 2021 18:42:12 +0000</pubDate>
      <link>https://dev.to/ezzylearning/a-guide-for-building-angular-spa-with-aspnet-core-5-web-api-d6p</link>
      <guid>https://dev.to/ezzylearning/a-guide-for-building-angular-spa-with-aspnet-core-5-web-api-d6p</guid>
      <description>&lt;p&gt;These days, it is a common trend to build a single page application (SPA) using a modern front-end web framework such as Angular, React, Vue, etc., and a server-side backend Web API. In this tutorial, I will walk you through a complete example of creating a single page application using Angular that will connect a server-side ASP.NET Core 5 Web API to fetch data from a SQL Server database using Entity Framework Core (Code First). At the end of this tutorial, you will be able to display some useful stats related to football players.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/AspNetCoreAngularSpaDemo" rel="noopener noreferrer"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Single Page Application (SPA)
&lt;/h2&gt;

&lt;p&gt;A single page application (SPA) is a type of web application that doesn’t load entire new pages from the server in an old and traditional way but instead loads data and contents from the server dynamically. SPA loads all necessary HTML, JavaScript, and CSS with a single page load, and the remaining resources are loaded dynamically usually from a backend Web API, and added to the page on different user actions. This technique results in an improved user experience because the user stays on the same page and control is never transferred to another page. Some popular examples of SPAs are Gmail, Facebook, Google Maps, Twitter, Pinterest, etc. There are many front-end frameworks to build SPAs and the most popular ones are &lt;a href="https://reactjs.org/" rel="noopener noreferrer"&gt;React&lt;/a&gt; by Facebook and &lt;a href="https://angular.io/" rel="noopener noreferrer"&gt;Angular&lt;/a&gt; by Google. Angular is the go-to option for developers who want to develop cross-platform, efficient, and sophisticated single-page apps using HTML, CSS, and TypeScript.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7d7ciwshy78djrqvkyo6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7d7ciwshy78djrqvkyo6.png" alt="Single Page Application (SPA)"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating Angular SPA in Visual Studio 2019
&lt;/h2&gt;

&lt;p&gt;Open Visual Studio 2019 and create a standard ASP.NET Core Web Application project. Make sure ASP.NET Core 5.0 version is selected and you are choosing &lt;strong&gt;ASP.NET Core with Angular&lt;/strong&gt; template as shown in the following screenshot.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjz4oum66kqcqcapev4o3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjz4oum66kqcqcapev4o3.png" alt="Create Angular Project in ASP.NET Core 5"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The above project template will generate a standard ASP.NET Core Web Application and a folder called &lt;strong&gt;ClientApp&lt;/strong&gt; that contains the Angular client-side application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6vm51g1z4jrfqjbj8pxc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6vm51g1z4jrfqjbj8pxc.png" alt="Angular Application Root Folder ClientApp in Visual Studio 2019"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You will also notice that a default Web API controller named &lt;strong&gt;WeatherForecastController&lt;/strong&gt; is also created for us in the Controllers folder that simply returns a list of &lt;strong&gt;WeatherForecast&lt;/strong&gt; objects that contains some random forecast information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    [HttpGet]
    public IEnumerable&amp;lt;WeatherForecast&amp;gt; Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index =&amp;gt; new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        }).ToArray();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before we start our implementation, the first thing we need to make sure is that we can run our Angular App in the browser and the app can load weather forecast information on the page. To do this, you need to install Angular CLI and need to run some commands.&lt;/p&gt;

&lt;p&gt;Right-click on the &lt;strong&gt;ClientApp&lt;/strong&gt; folder and choose the &lt;strong&gt;Open in Terminal&lt;/strong&gt; command from the context menu.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5wz5s5fvkeqw520bytbt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5wz5s5fvkeqw520bytbt.png" alt="Developer Powershell Window in Visual Studio 2019"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Visual Studio will open the Developer PowerShell window that can be used to run basic &lt;strong&gt;npm&lt;/strong&gt; package manager commands. Let’s install the Angular CLI with the following command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @angular/cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fczmwm78j9x3qmxy7bmwt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fczmwm78j9x3qmxy7bmwt.png" alt="Install Angular CLI using Developer Powershell in Visual Studio 2019"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, run the following command that will serve the Angular SPA in the browser.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run ng serve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzr8lyoakbfsld8bpbpn5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzr8lyoakbfsld8bpbpn5.png" alt="Run Angular App from Developer Powershell"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Press F5 to start debugging and now you should be able to see the Angular SPA app opening in the browser. The default Angular App has three pages &lt;strong&gt;Home&lt;/strong&gt;, &lt;strong&gt;Counter,&lt;/strong&gt; and &lt;strong&gt;Fetch data&lt;/strong&gt;. You can click the links shown on the navigation bar to navigate to these pages and notice that when you are navigating from one page to another page, there is no full page load from the server and the app is loading pages very quickly without a full postback to the server. Open the Fetch data page and you will notice that this page is calling the back end ASP.NET Core Web API and displaying weather information.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftoase80306pxuzfxzb26.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftoase80306pxuzfxzb26.png" alt="ASP.NET Core Angular SPA running in Browser"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So far, we haven’t written a single line of code and we are just running the default Angular SPA app created by Visual Studio. It is now time to implement our custom feature in this application. I will create a new page that will display the following information about some Football players.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuuiaaciyief9d5ul3zyd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuuiaaciyief9d5ul3zyd.png" alt="Angular Component Displaying Data from ASP.NET Core API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting Up Database with Entity Framework Core (Code First)
&lt;/h2&gt;

&lt;p&gt;We need to set up a database to store the player’s information and I have decided to use Entity Framework Code First approach for this tutorial. Install &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/a&gt;, &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Design" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.Design&lt;/a&gt; and &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.Tools&lt;/a&gt; NuGet packages in the project to perform some EF Core related development tasks.&lt;/p&gt;

&lt;p&gt;Next, we need to create our entity models and we normally put our models in the &lt;strong&gt;Models&lt;/strong&gt; folder by convention so let’s create a Models folder in the project root folder and create the following &lt;strong&gt;Player&lt;/strong&gt; model class. Notice, how I used &lt;strong&gt;[NotMapped]&lt;/strong&gt; attributes with some computed properties as I don’t want EF Core to generate database columns for those properties. The values of these properties can be calculated at runtime using the data available in other properties that’s why we normally don’t save such properties in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Player
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public int ShirtNo { get; set; }
    public int Appearances { get; set; }
    public int Goals { get; set; }
    public PlayerPositions Position { get; set; }

    [NotMapped]
    public string PositionName =&amp;gt; Position.ToString();

    [NotMapped]
    public decimal GoalsPerMatch =&amp;gt; Math.Round((decimal)Goals / (decimal)Appearances, 2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Player class also has a property Position which is an Enum type property so create the following enum in the Models folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public enum PlayerPositions
{
    Goalkeeper,
    Defender,
    Midfielder,
    Forward
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create a &lt;strong&gt;Data&lt;/strong&gt; folder in the project and create the DbContext class named &lt;strong&gt;FootballDbContext&lt;/strong&gt; in this folder. The DbContext is the most important class of Entity Framework because an instance of DbContext represents a session with the database which can be used to query and save instances of our entities to a database. I am also overriding the &lt;strong&gt;OnModelCreating&lt;/strong&gt; method to seed some player's information into the database table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FootballDbContext : DbContext
{
    public FootballDbContext(DbContextOptions&amp;lt;FootballDbContext&amp;gt; options)
        : base(options)
    {

    }

    public DbSet&amp;lt;Player&amp;gt; Players { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&amp;lt;Player&amp;gt;().HasData(
            new Player() { Id = 1, Name = "Juan Mata", ShirtNo = 8, Appearances  = 268, Goals = 54, Position = PlayerPositions.Forward},
            new Player() { Id = 2, Name = "Paul Pogba", ShirtNo = 6, Appearances  = 130, Goals = 28, Position = PlayerPositions.Midfielder},
            new Player() { Id = 3, Name = "David de Gea", ShirtNo = 1, Appearances  = 335, Goals = 0, Position = PlayerPositions.Goalkeeper},
            new Player() { Id = 4, Name = "Phil Jones", ShirtNo = 4, Appearances  = 200, Goals = 2, Position = PlayerPositions.Defender }
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to define our database connection string and we can save the connection string in the &lt;strong&gt;appsettings.json&lt;/strong&gt; file. Please note that you need to specify your database server name instead of &lt;strong&gt;DB_SERVER&lt;/strong&gt; in the following connection string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"ConnectionStrings": {
    "DefaultConnection": "Server=DB_SERVER; Database=FootballDb; Trusted_Connection=True; MultipleActiveResultSets=true"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to register the SQL Server database provider in &lt;strong&gt;Startup.cs&lt;/strong&gt; file using the UseSqlServer method. The &lt;strong&gt;UseSqlServer&lt;/strong&gt; method requires a database connection string and we can pass this information using the GetConnectionString method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // In production, the Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration =&amp;gt;
    {
        configuration.RootPath = "ClientApp/dist";
    });

    services.AddDbContext&amp;lt;FootballDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, we are ready to generate our database with the help of EF Core migrations. Migrations allow us to easily create a new database and then incrementally update the database schema to keep it in sync with the application models. You can run migrations using &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/dotnet" rel="noopener noreferrer"&gt;.NET Core CLI tools&lt;/a&gt; outside Visual Studio or you can use &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/powershell" rel="noopener noreferrer"&gt;Package Manager Console tools&lt;/a&gt; available in Visual Studio. For this tutorial, I will use Package Manager Console tools so let open Package Manager Console and add the following migration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Add-Migration InitialDbCreateAndSeedData
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;EF Core will create a directory called &lt;strong&gt;Migrations&lt;/strong&gt; in the project and will also generate some files in the folder. We are now ready to create our database and &lt;strong&gt;Player&lt;/strong&gt; table using the migrations code generated by EF Core. This can be done by running the following command in Package Manager Console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Update-Database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open SQL Server database and you should see a new database &lt;strong&gt;FootballDb&lt;/strong&gt; in the list of databases and if you will open the &lt;strong&gt;Players&lt;/strong&gt; table you will see all of our data is seeded in the table. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2hcgu9394cnquryh3kwp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2hcgu9394cnquryh3kwp.png" alt="Players Database Created using EF Core Code First Migrations"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to learn EF Code First in detail then you can read my post &lt;a href="https://www.ezzylearning.net/tutorial/data-access-in-asp-net-core-using-ef-core-code-first" rel="noopener noreferrer"&gt;Data Access in ASP.NET Core using EF Core (Code First)&lt;/a&gt;. I also have a post about EF Core Database First  &lt;a href="https://www.ezzylearning.net/tutorial/data-access-in-asp-net-core-using-ef-core-database-first" rel="noopener noreferrer"&gt;Data Access in ASP.NET Core using EF Core (Database First)&lt;/a&gt; in case you are interested.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating ASP.NET Core Web API for Angular SPA
&lt;/h2&gt;

&lt;p&gt;Angular apps can make Ajax based server-side calls and load and display data from backend APIs. We need to create an ASP.NET Core Web API to return Player's data that can be consumed by the Angular front-end app. Let’s create an API Controller &lt;strong&gt;PlayerController&lt;/strong&gt; in the Controllers folder and inject &lt;strong&gt;FootballDbContext&lt;/strong&gt; in the constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ApiController]
[Route("api/[controller]")]
public class PlayerController : ControllerBase
{
    private readonly FootballDbContext _context;

    public PlayerController(FootballDbContext context)
    {
        _context = context;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, implement the following &lt;strong&gt;GetPlayers&lt;/strong&gt; method which is simply returning all players from the Player table we created above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[HttpGet]
public async Task&amp;lt;ActionResult&amp;lt;IEnumerable&amp;lt;Player&amp;gt;&amp;gt;&amp;gt; GetPlayers()
{
    return await _context.Players.ToListAsync();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the browser and test the API by adding &lt;strong&gt;api/Player&lt;/strong&gt; in the URL as shown below. You should be able to see the player's data in JSON format.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbpyoa6njz0t15zc99xkw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbpyoa6njz0t15zc99xkw.png" alt="ASP.NET Core Web API in Angular SPA Application"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to learn more about ASP.NET Core Web APIs then read my tutorial &lt;a href="https://www.ezzylearning.net/tutorial/a-developers-guide-for-creating-web-apis-with-asp-net-core-5" rel="noopener noreferrer"&gt;A Developer’s Guide for Creating Web APIs with ASP.NET Core 5&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating Angular Component to Consume ASP.NET Core Web API
&lt;/h2&gt;

&lt;p&gt;Angular is a modular framework which means modules are the basic building block of the angular app. Each app must have at least one module which is called the root module and by default, it is defined in the &lt;strong&gt;app.module.ts&lt;/strong&gt; file available in &lt;strong&gt;ClientApp/src/app&lt;/strong&gt; folder&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fax1ktmh9ov86ljh7fe11.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fax1ktmh9ov86ljh7fe11.png" alt="app folder in angular application"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Angular modules can define both the components and services in them. Components are used to define different parts of the application. For example, in the above screenshot, you can see that all three pages of our Angular App &lt;strong&gt;Home&lt;/strong&gt;, &lt;strong&gt;Counter,&lt;/strong&gt; and &lt;strong&gt;Fetch data&lt;/strong&gt; are defined as components and all of these components have their folders within the &lt;strong&gt;app&lt;/strong&gt; folder with the names &lt;strong&gt;home&lt;/strong&gt;, &lt;strong&gt;counter,&lt;/strong&gt; and &lt;strong&gt;fetch-data.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A component consists of a view and a TypeScript class where the view defines the look and feel of the component using HTML and CSS and the class defines the functionality/behavior of the component using TypeScript. Every app must have at least one component also called root components and usually available in &lt;strong&gt;app.component.ts&lt;/strong&gt; file also shown in the above screenshot.&lt;/p&gt;

&lt;p&gt;For our app, we want to add another component &lt;strong&gt;player&lt;/strong&gt; that will display all players coming from a backend Web API. You can add a new component from the command prompt using the following Angular CLI command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng generate component player
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don’t want to use Angular CLI you can also add a &lt;strong&gt;player&lt;/strong&gt; folder in the &lt;strong&gt;app&lt;/strong&gt; folder and add the following two files manually.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;player.component.ts&lt;/li&gt;
&lt;li&gt;player.component.html&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Open the player.component.ts file and define your component as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-player',
  templateUrl: './player.component.html'
})
export class PlayerComponent {
  public players: Player[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get&amp;lt;Player[]&amp;gt;(baseUrl + 'api/Player').subscribe(result =&amp;gt; {
      this.players = result;
    }, error =&amp;gt; console.error(error));
  }
}

interface Player {
  id: number;
  name: string;
  shirtNo: number;
  appearances: number;
  goals: number;
  positionName: number;
  goalsPerMatch: number;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;PlayerComponent&lt;/strong&gt; class is calling our &lt;strong&gt;api/Player&lt;/strong&gt; Web API using &lt;strong&gt;HttpClient&lt;/strong&gt; and initializing the &lt;strong&gt;player's&lt;/strong&gt; property of the class with the data loaded from the backend. We can now use this &lt;strong&gt;player's&lt;/strong&gt; property in the view file &lt;strong&gt;player.component.html&lt;/strong&gt; attached with the component using the &lt;strong&gt;templateUrl&lt;/strong&gt; option.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h1 id="tableLabel"&amp;gt;Football Players&amp;lt;/h1&amp;gt;
&amp;lt;p *ngIf="!players"&amp;gt;&amp;lt;em&amp;gt;Loading...&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;table class='table table-striped' aria-labelledby="tableLabel" *ngIf="players"&amp;gt;
   &amp;lt;thead&amp;gt;
      &amp;lt;tr&amp;gt;
         &amp;lt;th&amp;gt;Shirt No&amp;lt;/th&amp;gt;
         &amp;lt;th&amp;gt;Name&amp;lt;/th&amp;gt;
         &amp;lt;th&amp;gt;Position&amp;lt;/th&amp;gt;
         &amp;lt;th&amp;gt;Appearances&amp;lt;/th&amp;gt;
         &amp;lt;th&amp;gt;Goals&amp;lt;/th&amp;gt;
         &amp;lt;th&amp;gt;Goals per match&amp;lt;/th&amp;gt;
      &amp;lt;/tr&amp;gt;
   &amp;lt;/thead&amp;gt;
   &amp;lt;tbody&amp;gt;
      &amp;lt;tr *ngFor="let player of players"&amp;gt;
         &amp;lt;td&amp;gt;{{ player.shirtNo }}&amp;lt;/td&amp;gt;
         &amp;lt;td&amp;gt;{{ player.name }}&amp;lt;/td&amp;gt;
         &amp;lt;td&amp;gt;{{ player.positionName }}&amp;lt;/td&amp;gt;
         &amp;lt;td&amp;gt;{{ player.appearances }}&amp;lt;/td&amp;gt;
         &amp;lt;td&amp;gt;{{ player.goals }}&amp;lt;/td&amp;gt;
         &amp;lt;td&amp;gt;{{ player.goalsPerMatch }}&amp;lt;/td&amp;gt;
      &amp;lt;/tr&amp;gt;
   &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above view code is also pretty straightforward. I am using &lt;strong&gt;ngif&lt;/strong&gt; directive to render Loading… if players' property is not yet initialized. The ngif directive conditionally includes a template based on the value of an expression. If the expression evaluates to true, Angular renders the template.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;p *ngIf="!players"&amp;gt;&amp;lt;em&amp;gt;Loading...&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next important piece of code is where I am using &lt;strong&gt;ngFor&lt;/strong&gt; to iterate all the &lt;strong&gt;players&lt;/strong&gt; and displaying each player property in standard HTML &lt;strong&gt;td&lt;/strong&gt; element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;tr *ngFor="let player of players"&amp;gt;
   &amp;lt;td&amp;gt;{{ player.shirtNo }}&amp;lt;/td&amp;gt;
   &amp;lt;td&amp;gt;{{ player.name }}&amp;lt;/td&amp;gt;
   &amp;lt;td&amp;gt;{{ player.positionName }}&amp;lt;/td&amp;gt;
   &amp;lt;td&amp;gt;{{ player.appearances }}&amp;lt;/td&amp;gt;
   &amp;lt;td&amp;gt;{{ player.goals }}&amp;lt;/td&amp;gt;
   &amp;lt;td&amp;gt;{{ player.goalsPerMatch }}&amp;lt;/td&amp;gt;
&amp;lt;/tr&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once our player component is complete, we need to register it in app.module where all application modules are declared.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { PlayerComponent } from './player/player.component';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent,
    PlayerComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent },
      { path: 'player', component: PlayerComponent }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, you need to add a new menu item on top of the page so that you can navigate to the players component and see list of players. Open the &lt;strong&gt;nav-menu.component.html&lt;/strong&gt; file and declare the &lt;strong&gt;Players&lt;/strong&gt; menu item as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ul class="navbar-nav flex-grow"&amp;gt;
    &amp;lt;li class="nav-item" [routerLinkActive]="['link-active']" [routerLinkActiveOptions]="{ exact: true }"&amp;gt; &amp;lt;a class="nav-link text-dark" [routerLink]="['/']"&amp;gt;Home&amp;lt;/a&amp;gt; &amp;lt;/li&amp;gt;
    &amp;lt;li class="nav-item" [routerLinkActive]="['link-active']"&amp;gt; &amp;lt;a class="nav-link text-dark" [routerLink]="['/counter']"&amp;gt;Counter&amp;lt;/a&amp;gt; &amp;lt;/li&amp;gt;
    &amp;lt;li class="nav-item" [routerLinkActive]="['link-active']"&amp;gt; &amp;lt;a class="nav-link text-dark" [routerLink]="['/fetch-data']"&amp;gt;Fetch data&amp;lt;/a&amp;gt; &amp;lt;/li&amp;gt;
    &amp;lt;li class="nav-item" [routerLinkActive]="['link-active']"&amp;gt; &amp;lt;a class="nav-link text-dark" [routerLink]="['/player']"&amp;gt;Players&amp;lt;/a&amp;gt; &amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have written lots of code and it is now time to see everything in action. Run the application using the method specified at the start of this tutorial and click the Players menu item shown on top of the page. You should see the page similar to the following with all player’s information.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuuiaaciyief9d5ul3zyd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuuiaaciyief9d5ul3zyd.png" alt="Angular Component Displaying Data from ASP.NET Core API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Angular is a powerful front-end framework for building interactive model applications and when you combine this with the ASP.NET Core Web APIs backend, you can build some seriously amazing apps. In this tutorial, I have just covered the basics of combining Angular with ASP.NET Core. There is a lot more to explore and I will try to write more useful posts on these two technologies. If you have enjoyed this post, please share it with others and spread the knowledge.&lt;/p&gt;

</description>
      <category>angular</category>
      <category>aspnetcore</category>
      <category>webapi</category>
      <category>spa</category>
    </item>
    <item>
      <title>How to Use JQuery DataTables with ASP.NET Core Web API</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Sat, 18 Sep 2021 17:16:02 +0000</pubDate>
      <link>https://dev.to/ezzylearning/how-to-use-jquery-datatables-with-asp-net-core-web-api-1bcg</link>
      <guid>https://dev.to/ezzylearning/how-to-use-jquery-datatables-with-asp-net-core-web-api-1bcg</guid>
      <description>&lt;p&gt;JQuery &lt;a href="https://datatables.net/" rel="noopener noreferrer"&gt;DataTables&lt;/a&gt; plugin is one of the most powerful and famous plugins for creating tabular data grids. It has built-in support for searching, sorting, and pagination without any configuration and there are so many ways to customize this data grid as per your requirements. It also has some advanced features such as support for AJAX, server-side processing, and styling according to some of the popular frameworks e.g. Bootstrap, Material Design, etc. In one of my old tutorials &lt;a href="https://www.ezzylearning.net/tutorial/using-jquery-datatables-with-asp-net-web-api" rel="noopener noreferrer"&gt;Using JQuery DataTables with ASP.NET Web API&lt;/a&gt;, I demonstrated how to connect &lt;a href="https://datatables.net/" rel="noopener noreferrer"&gt;DataTables&lt;/a&gt; with ASP.NET Web API. Many of my readers requested me to write an updated version of that tutorial for ASP.NET Core so in this tutorial, I will show you how you can use JQuery &lt;a href="https://datatables.net/" rel="noopener noreferrer"&gt;DataTables&lt;/a&gt; with ASP.NET Core Web API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Configure Entity Framework Core to Fetch Data
&lt;/h2&gt;

&lt;p&gt;Let’s start by creating a new ASP.NET Core MVC Web Application project in Visual Studio 2019 using the standard &lt;strong&gt;File &amp;gt; New &amp;gt; Project&lt;/strong&gt; menu option. I have decided to use Microsoft’s popular &lt;strong&gt;AdventureWorks&lt;/strong&gt; sample database for this tutorial and you can download this database from the &lt;a href="https://docs.microsoft.com/en-us/sql/samples/adventureworks-install-configure?view=sql-server-ver15&amp;amp;tabs=ssms" rel="noopener noreferrer"&gt;Microsoft website&lt;/a&gt;. I will be using the following &lt;strong&gt;Product&lt;/strong&gt; table from the AdventureWorks database and we will load its data using ASP.NET Core Web API and then finally we will display it on a page using the DataTables plugin.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvsjo7q8m8vc0edsz7k7n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvsjo7q8m8vc0edsz7k7n.png" alt="Product Table in AdventureWorks Database"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I will be using Entity Framework Core (Database First) approach to quickly generate entity model class for the above Product Table and DbContext object. For this purpose, we need to install  &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/a&gt; NuGet package as well as &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Design" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.Design&lt;/a&gt; and &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.Tools&lt;/a&gt; NuGet packages to perform some Entity Framework Core design-time development tasks. If you don’t know how to install NuGet packages then read my tutorial &lt;a href="https://www.ezzylearning.net/tutorial/working-with-packages-and-libraries-in-asp-net-core" rel="noopener noreferrer"&gt;Working with Packages and Libraries in ASP.NET Core&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Once the above NuGet packages are installed, generate the entity model class and DbContext using the following &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/powershell#scaffold-dbcontext" rel="noopener noreferrer"&gt;Scaffold-DbContext&lt;/a&gt; command in Package Manager Console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Scaffold-DbContext -Connection "Server=DB_SERVER; Database=AdventureWorks; Trusted_Connection=True; MultipleActiveResultSets=true;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir "Models" -ContextDir "Data" -Context "AdventureWorksDbContext" -Tables "Product" -NoOnConfiguring
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The command has the connection string information and some other parameters and it will generate the &lt;strong&gt;Product&lt;/strong&gt; class in the &lt;strong&gt;Models&lt;/strong&gt; folder and &lt;strong&gt;AdventureWorksDbContext&lt;/strong&gt; class in the &lt;strong&gt;Data&lt;/strong&gt; folder. I also used &lt;strong&gt;–Tables&lt;/strong&gt; option with the value Product because for this tutorial, I only want to generate a Product table entity class.&lt;/p&gt;

&lt;p&gt;Next, we need to specify the connection string in appsettings.json file as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
   "ConnectionStrings":{
      "DefaultConnection":"Server=DB_SERVER; Database=AdventureWorks; Trusted_Connection=True; MultipleActiveResultSets=true"
   },
   "Logging":{
      "LogLevel":{
         "Default":"Information",
         "Microsoft":"Warning",
         "Microsoft.Hosting.Lifetime":"Information"
      }
   },
   "AllowedHosts":"*"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Entity Framework provider can be configured in &lt;strong&gt;ConfigureServices&lt;/strong&gt; method of &lt;strong&gt;Startup.cs&lt;/strong&gt; file as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDbContext&amp;lt;AdventureWorksDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want’ to learn more about using Entity Framework, then you can read my tutorials &lt;a href="https://www.ezzylearning.net/tutorial/data-access-in-asp-net-core-using-ef-core-database-first" rel="noopener noreferrer"&gt;Data Access in ASP.NET Core using EF Core (Database First)&lt;/a&gt; and &lt;a href="https://www.ezzylearning.net/tutorial/data-access-in-asp-net-core-using-ef-core-code-first" rel="noopener noreferrer"&gt;Data Access in ASP.NET Core using EF Core (Code First)&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Loading Data using ASP.NET Core Web API
&lt;/h2&gt;

&lt;p&gt;JQuery DataTables can make Ajax based server-side calls and load and display data from backend APIs. We need to create a Web API in ASP.NET Core and need to return data in the format that is acceptable by the DataTables plugin. Let’s create an API Controller &lt;strong&gt;ProductsController&lt;/strong&gt; in the Controllers folder and inject &lt;strong&gt;AdventureWorksDbContext&lt;/strong&gt; in the constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly AdventureWorksDbContext _context;

    public ProductsController(AdventureWorksDbContext context)
    {
        _context = context;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we will implement the following &lt;strong&gt;GetProducts&lt;/strong&gt; method which is simply returning all products from the Product table available in AdventureWorks database&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// GET: api/Products
[HttpGet]
public async Task&amp;lt;ActionResult&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt;&amp;gt; GetProducts()
{
    return await _context.Products.ToListAsync();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the browser and test the API by adding &lt;strong&gt;api/Products&lt;/strong&gt; in the URL as shown below. You should be able to see the product data available in JSON format.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faygxmc3b2ht16ws91knh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faygxmc3b2ht16ws91knh.png" alt="Web API returns JSON for DataTables"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to learn more about ASP.NET Core Web APIs then read my tutorial &lt;a href="https://www.ezzylearning.net/tutorial/a-developers-guide-for-creating-web-apis-with-asp-net-core-5" rel="noopener noreferrer"&gt;A Developer’s Guide for Creating Web APIs with ASP.NET Core 5&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Installing JQuery DataTables Plugin in ASP.NET Core
&lt;/h2&gt;

&lt;p&gt;It is now time to download the JQuery DataTables plugin and include it in our project. At the time of writing this tutorial, the latest version of the plugin is 1.10.21 and it can be downloaded from the DataTables website and added to &lt;strong&gt;wwwroot&lt;/strong&gt; folder of the project manually. You can also use the &lt;strong&gt;LibMan&lt;/strong&gt; tool to install and add the DataTables plugin in the project without leaving the Visual Studio. If you want to learn more about installing client-side libraries in ASP.NET Core applications then read my tutorial &lt;a href="https://www.ezzylearning.net/tutorial/working-with-packages-and-libraries-in-asp-net-core" rel="noopener noreferrer"&gt;Working with Packages and Libraries in ASP.NET Core&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Right-click the project name in solution explorer and choose &lt;strong&gt;Add &amp;gt; Client-Side Library…&lt;/strong&gt; menu option. Type &lt;strong&gt;datatables@&lt;/strong&gt; in the &lt;strong&gt;Library&lt;/strong&gt; field and you should see all the available versions. Select &lt;strong&gt;&lt;a href="mailto:datatables@1.10.21"&gt;datatables@1.10.21&lt;/a&gt;&lt;/strong&gt; version and keep &lt;strong&gt;Include all library files&lt;/strong&gt; option selected to download all files related to DataTables plugin. Clicking the Install button will download the plugin files and they will be added in a new &lt;strong&gt;datatables&lt;/strong&gt; folder in &lt;strong&gt;wwwroot/lib&lt;/strong&gt; folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6w286v83hp4oghjlswqk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6w286v83hp4oghjlswqk.png" alt="Install DataTables in ASP.NET Core using Libman in Visual Studio 2019"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please keep in mind that DataTables is a JQuery plugin and we need JQuery library to use DataTables. Luckily, Visual Studio automatically adds JQuery library in every new ASP.NET Core MVC Web application so we don’t need to download it again using the LibMan tool.&lt;/p&gt;

&lt;p&gt;To use DataTables plugin, we need to include plugin related CSS stylesheets and the best place to add these stylesheets is the &lt;strong&gt;&lt;/strong&gt; element of the &lt;strong&gt;_Layout.cshtml&lt;/strong&gt; file. Include &lt;strong&gt;jquery.dataTables.css&lt;/strong&gt; and &lt;strong&gt;dataTables.bootstrap4.css&lt;/strong&gt; stylesheets as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;head&amp;gt;
    &amp;lt;meta charset="utf-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;@ViewData["Title"]&amp;lt;/title&amp;gt;

    &amp;lt;link href="~/lib/datatables/css/jquery.dataTables.css" rel="stylesheet" /&amp;gt;
    &amp;lt;link href="~/lib/datatables/css/dataTables.bootstrap4.css" rel="stylesheet" /&amp;gt;

    &amp;lt;link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /&amp;gt;
    &amp;lt;link rel="stylesheet" href="~/css/site.css" /&amp;gt;
&amp;lt;/head&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The file &lt;strong&gt;jquery.dataTables.css&lt;/strong&gt; is the main plugin file and the &lt;strong&gt;dataTables.bootstrap4.css&lt;/strong&gt; file will be used to apply bootstrap 4 look and feel to the generated data grid. You also have the options to choose the look and feel of some popular CSS frameworks such as Foundations, SemanticUI, Material Design, etc.&lt;/p&gt;

&lt;p&gt;We also need to add the plugin related JavaScript files such a &lt;strong&gt;jquery.dataTables.min.js&lt;/strong&gt; and these files can be added just before the closing &lt;strong&gt;&lt;/strong&gt; element in the &lt;strong&gt;_Layout.cshtml&lt;/strong&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script src="~/lib/jquery/dist/jquery.js"&amp;gt;&amp;lt;/script&amp;gt;

    &amp;lt;script src="~/lib/datatables/js/jquery.dataTables.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/lib/datatables/js/dataTables.bootstrap4.js"&amp;gt;&amp;lt;/script&amp;gt;

    &amp;lt;script src="~/lib/bootstrap/dist/js/bootstrap.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/js/site.js" asp-append-version="true"&amp;gt;&amp;lt;/script&amp;gt;

    @await RenderSectionAsync("Scripts", required: false)
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Configuring JQuery DataTables Plugin in ASP.NET Core
&lt;/h2&gt;

&lt;p&gt;We are finally ready to use the JQuery DataTables plugin on our page. The plugin normally works with HTML tables so add the following table markup in Index.cshtml file. The markup is using basic bootstrap table classes such as table-bordered, table-striped, etc. I want to display five columns of the Product table so I only included those column headers in the table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@{
    ViewData["Title"] = "Home Page";
}
&amp;lt;h2&amp;gt;Products&amp;lt;/h2&amp;gt;
&amp;lt;table id="example" class="table table-sm table-bordered table-striped" style="width:100%"&amp;gt;
    &amp;lt;thead&amp;gt;
        &amp;lt;tr&amp;gt;
            &amp;lt;th&amp;gt;Product Id&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Name&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Product Number&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Color&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;List Price&amp;lt;/th&amp;gt;
        &amp;lt;/tr&amp;gt;
    &amp;lt;/thead&amp;gt;
&amp;lt;/table&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next step is to initialize the DataTables plugin on the page with some basic configurations. Add the following script in the &lt;strong&gt;site.js&lt;/strong&gt; file and make sure that the id in our script matches the table id &lt;strong&gt;example&lt;/strong&gt; in the HTML. The important setting in the following code snippet is the &lt;strong&gt;ajax&lt;/strong&gt; which specifies the URL of the Web API we just created above. This setting will be used by the DataTables plugin to fetch and bind data. We also used that &lt;strong&gt;columns&lt;/strong&gt; setting that specifies which data fields to use to generate the columns of the grid. You can read about all the available settings in the plugin manual &lt;a href="https://datatables.net/manual" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$(document).ready(function () {
    $('#example').DataTable({
        processing: true,
        ordering: true,
        paging: true,
        searching: true,
        ajax: "api/Products",
        columns: [
            { "data": "productId" },
            { "data": "name" },
            { "data": "productNumber" },
            { "data": "color" },
            { "data": "listPrice" }
        ]
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;DataTables can be used in two different modes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Client-side – Filtering, paging, and sorting are done in the web-browser.&lt;/li&gt;
&lt;li&gt;Server-side – Filtering, paging, and sorting calculations are performed on the server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By default, the DataTables operates on client-side processing mode, but can it be configured to operate in server-side processing mode. When operating in server-side mode, the DataTables plugin sends some parameters to the server indicating what data it needs, what page number to read, what filters to apply on data, etc. and also expects data to come back in a specific format so that it has all the information to display the table. We need to make sure that our ASP.NET Web API method &lt;strong&gt;GetProducts&lt;/strong&gt; send all the parameters understood by the DataTables plugin. If you will run your project now, you will see that no data is displayed on the page and there is also the following error shown in the browser console.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqpyi1hvnlqi215kchqfa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqpyi1hvnlqi215kchqfa.png" alt="DataTables plugin shows error when server send bad response. Cannot read property 'length' of undefined"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To fix the above error we need to send data in plugin readable format. Following is the list of parameters DataTables expects will return from the server-side. More detail about these parameters can be found in the DataTables &lt;a href="https://datatables.net/manual" rel="noopener noreferrer"&gt;manual&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmclfu60f22t1vs0vzinh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmclfu60f22t1vs0vzinh.png" alt="DataTables Response Parameters from Official Datatables docs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We need to make sure our product data is wrapped and returned in the &lt;strong&gt;data&lt;/strong&gt; parameter specified above. Let’s create a model class &lt;strong&gt;DataTableResponse&lt;/strong&gt; in the Models folder and declare all of the above parameters as properties in the class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DataTableResponse
{
    public int Draw { get; set; }
    public long RecordsTotal { get; set; }
    public int RecordsFiltered { get; set; }
    public object[] Data { get; set; }
    public string Error { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to adjust the code of the &lt;strong&gt;GetProducts&lt;/strong&gt; method and need to return the &lt;strong&gt;DataTableResponse&lt;/strong&gt; objects instead of the List of Product objects. The code snippet below shows how to wrap the products in the DataTableResponse object along with other properties.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// GET: api/Products
[HttpGet]
public async Task&amp;lt;ActionResult&amp;lt;DataTableResponse&amp;gt;&amp;gt; GetProducts()
{
    var products = await _context.Products.ToListAsync();

    return new DataTableResponse
    {
        RecordsTotal = products.Count(),
        RecordsFiltered = 10,
        Data = products.ToArray()
    };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Build and run the project again and this time you will see the following grid rendered in the browser.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnx9459r7tvj7zsy8811k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnx9459r7tvj7zsy8811k.png" alt="JQuery DataTables showing Data in using ASP.NET Web API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;JQuery DataTables is a highly flexible and feature-rich plugin with hundreds of features. The Datatables also supports additional plugins that can be plugged with the DataTables and add even more functionality. There is also a powerful and feature-rich API available which can provide you even more ways to use DataTables plugins programmatically. It is impossible to discuss all plugin features in a single tutorial but I hope this tutorial will put you on the right track.&lt;/p&gt;

</description>
      <category>jquery</category>
      <category>datatables</category>
      <category>aspnetcore</category>
      <category>webapi</category>
    </item>
    <item>
      <title>Data Access in ASP.NET Core using EF Core (Database First)</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Mon, 13 Sep 2021 17:55:07 +0000</pubDate>
      <link>https://dev.to/ezzylearning/data-access-in-asp-net-core-using-ef-core-database-first-4i4f</link>
      <guid>https://dev.to/ezzylearning/data-access-in-asp-net-core-using-ef-core-database-first-4i4f</guid>
      <description>&lt;p&gt;In my previous tutorial &lt;a href="https://www.ezzylearning.net/tutorial/data-access-in-asp-net-core-using-ef-core-code-first"&gt;Data Access in ASP.NET Core 5 using EF Core 5 (Code First)&lt;/a&gt;, I covered the basics of Entity Framework and DbContext and showed you how to use the Code First technique to generate a new database using the entity models. You can use Code First approach if you are starting a new project but it is not always the case in the real world. Sometimes you already have a database and you have to use Entity Framework with an existing database. Entity Framework Core support this approach as well and in this tutorial, I will demonstrate different techniques for generating DbContext and model classes from an existing database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/AspNetCoreEfCoreDatabaseFirstDemo"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started with EF Core using Existing Database
&lt;/h2&gt;

&lt;p&gt;For this tutorial, I will be using the following database that has the Customers, Products, Orders, and ProductOrders table with a standard parent-child relationship.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--KHqL6bA0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnmifwvsnbwvlvr72agj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KHqL6bA0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnmifwvsnbwvlvr72agj.png" alt="Entity-Framework-Core-Entity-Model-Db-Design"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Create a standard ASP.NET Core 5 MVC Web Application and install Entity Framework Core and SQL Server Data Provider by installing &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/"&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/a&gt; NuGet package. We also need to install &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Design"&gt;Microsoft.EntityFrameworkCore.Design&lt;/a&gt; and &lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/"&gt;Microsoft.EntityFramewo&lt;/a&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/"&gt;r&lt;/a&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/"&gt;kCore.Tools&lt;/a&gt; to perform some Entity Framework Core design-time development tasks such as generating the DbContext and Entity Models from an existing database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generating Models from an Existing Database using EF Core
&lt;/h2&gt;

&lt;p&gt;Entity Framework Core doesn’t support the visual designer (.edmx file) for creating models which we were using in the old version of Entity Framework (EF 6). In Entity Framework Core, we need to generate Model classes from an existing database using the following two options.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If you are using Visual Studio, you can use the &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/powershell#scaffold-dbcontext"&gt;Package Manager Console (PMC) tools&lt;/a&gt; for Entity Framework Core&lt;/li&gt;
&lt;li&gt;If you are not using Visual Studio, you can use the cross-platform &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/dotnet"&gt;EF Core Command-line Tools&lt;/a&gt; from a command prompt&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For this tutorial, I am using Package Manager Console Tools so the main command you need to reverse engineer the models from the existing database schema is &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/powershell#scaffold-dbcontext"&gt;&lt;strong&gt;Scaffold-DbContext&lt;/strong&gt;&lt;/a&gt;. Please note that for Scaffold-DbContext to generate an entity type, the database table must have a primary key. This command has many options to customize the generated code. The following table shows all available parameters for &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/powershell#scaffold-dbcontext"&gt;&lt;strong&gt;Scaffold-DbContext&lt;/strong&gt;&lt;/a&gt;command.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Parameter&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Description&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;-Connection &lt;/td&gt;
&lt;td&gt;This parameter specifies the connection string to the database. If you are using ASP.NET Core 2.x or higher version, then you can also give the value as &lt;strong&gt;name=&lt;/strong&gt; in which case the &lt;strong&gt;name&lt;/strong&gt; comes from the configuration sources that are set up for the project. This is a positional parameter and is required.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-Provider &lt;/td&gt;
&lt;td&gt;This parameter specifies the database provider we want to use. We normally provide the name of the NuGet package, for example, &lt;strong&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/strong&gt; can be used for the SQL Server database. This is a positional parameter and is required.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-OutputDir &lt;/td&gt;
&lt;td&gt;This command specifies the directory to put the generated files in. This path is relative to the project directory.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-ContextDir &lt;/td&gt;
&lt;td&gt;This parameter specifies the directory to put the DbContext file in. This path is also relative to the project directory.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-Namespace &lt;/td&gt;
&lt;td&gt;The parameter is added in Entity Framework Core 5.0 and it specifies the namespace to use for all generated classes. By default, the root namespace and the output directory will be used.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-ContextNamespace &lt;/td&gt;
&lt;td&gt;The parameter is also added in Entity Framework Core 5.0 and it specifies the namespace to use for the generated DbContext class. This parameter overrides –Namespace which means you can have a different namespace for DbContext generated class than the generated models.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-Context &lt;/td&gt;
&lt;td&gt;This parameter specifies the name of the DbContext class to generate.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-Schemas &lt;/td&gt;
&lt;td&gt;The schemas of tables to generate entity types for. If this parameter is omitted, all schemas are included.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-Tables &lt;/td&gt;
&lt;td&gt;The tables to generate entity types for. If this parameter is omitted, all tables are included. The example for generating code of specific tables is –Tables “Product, Customer”&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-DataAnnotations&lt;/td&gt;
&lt;td&gt;This parameter specifies whether we want to use Data Annotation attributes to configure the models. If this parameter is omitted, the generated code will use fluent API to configure models.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-UseDatabaseNames&lt;/td&gt;
&lt;td&gt;Use table and column names exactly as they appear in the database. If this parameter is omitted, database names are changed to more closely conform to C# name style conventions.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-Force&lt;/td&gt;
&lt;td&gt;Overwrite existing files.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-NoOnConfiguring&lt;/td&gt;
&lt;td&gt;The parameter is added in Entity Framework Core 5.0 and it specifies whether we want to generate DbContext.OnConfiguring method in our generated DbContext class or not.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;-NoPluralize&lt;/td&gt;
&lt;td&gt;The parameter is added in Entity Framework Core 5.0 and it specifies if we want to pluralize the DbSet classes e.g. Product or Products&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Let’s try to use some of the parameters from the above table. Open the Package Manager Console of the project and copy/paste the following command and press Enter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Scaffold-DbContext -Connection "Server=DESKTOP-6SDKTRC; Database=OnlineShopDb; Trusted_Connection=True; MultipleActiveResultSets=true;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir "Models" -ContextDir "Data" -Context "OnlineShopDbContext"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BHLPw2qd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tiqa46m56rmzshfl6mgi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BHLPw2qd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tiqa46m56rmzshfl6mgi.png" alt="Scaffold-DbContext command in Package Manager Console in Visual Studio"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I am providing connection string as per my database so you need to change the server and database name in the connection string as per your machine. I also specified SQL Server provider because I am using SQL Server database. I want to generate all my model classes in the &lt;strong&gt;Models&lt;/strong&gt; folder and I want my DbContext to be generated in the &lt;strong&gt;Data&lt;/strong&gt; folder with the name &lt;strong&gt;OnlineShopDbContext&lt;/strong&gt;. Once the command will execute you will see the generated classes in Solution Explorer.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qU-B2Z9L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekuc2srb93snj8fbw6ug.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qU-B2Z9L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekuc2srb93snj8fbw6ug.png" alt="Generated Models and DbContext classes using EF Core Database First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The generated model classes such as Product, Customer, etc. are simple C# classes with the properties mapped to database table columns. Here is the example of a Customer class generated from the Customer table in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public partial class Customer
{
    public Customer()
    {
        Orders = new HashSet&amp;lt;Order&amp;gt;();
    }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }

    public virtual ICollection&amp;lt;Order&amp;gt; Orders { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code generated in the &lt;strong&gt;OnlineShopDbContext&lt;/strong&gt; class is more interesting. The class is inheriting from DbContext class as expected and it has &lt;strong&gt;DbSet&lt;/strong&gt; properties for each table in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public partial class OnlineShopDbContext : DbContext
{
    public OnlineShopDbContext()
    {
    }

    public OnlineShopDbContext(DbContextOptions&amp;lt;OnlineShopDbContext&amp;gt; options)
        : base(options)
    {
    }

    public virtual DbSet&amp;lt;Customer&amp;gt; Customers { get; set; }
    public virtual DbSet&amp;lt;Order&amp;gt; Orders { get; set; }
    public virtual DbSet&amp;lt;Product&amp;gt; Products { get; set; }
    public virtual DbSet&amp;lt;ProductOrder&amp;gt; ProductOrders { get; set; }

    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is also an overridden method &lt;strong&gt;OnConfiguring&lt;/strong&gt; which is configuring the Entity Framework using the &lt;strong&gt;UseSqlServer&lt;/strong&gt; method. You can see that a warning is also generated telling you that you should not save sensitive information such as connection string in the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        #warning To protect potentially sensitive information in your connection string, 
        you should move it out of source code. You can avoid scaffolding the connection 
        string by using the Name= syntax to read it from configuration - see 
        https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on 
        storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.

        optionsBuilder.UseSqlServer("Server=DESKTOP-6SDKTRC; Database=OnlineShopDb; Trusted_Connection=True; MultipleActiveResultSets=true;");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s first fix this issue as we want to follow the best practices. Run the following command with two additional parameters &lt;strong&gt;–NoOnConfiguring&lt;/strong&gt; and &lt;strong&gt;–Force&lt;/strong&gt; and you will see that this time &lt;strong&gt;OnConfiguring&lt;/strong&gt; method will not be generated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Scaffold-DbContext -Connection "Server=DESKTOP-6SDKTRC; Database=OnlineShopDb; Trusted_Connection=True; MultipleActiveResultSets=true;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir "Models" -ContextDir "Data" -Context "OnlineShopDbContext" -NoOnConfiguring –Force
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can specify the connection string in &lt;strong&gt;appsettings.json&lt;/strong&gt; file as follows&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-6SDKTRC; Database=OnlineShopDb; Trusted_Connection=True; MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "\*"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Entity Framework provider can be configured in &lt;strong&gt;ConfigureServices&lt;/strong&gt; method of &lt;strong&gt;Startup.cs&lt;/strong&gt; file as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDbContext&amp;lt;OnlineShopDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to learn more about ASP.NET Core Configuration then read my post &lt;a href="https://www.ezzylearning.net/tutorial/a-step-by-step-guide-for-asp-net-core-configuration"&gt;A Step by Step Guide for ASP.NET Core Configuration&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The next overridden method in the &lt;strong&gt;OnlineShopDbContext&lt;/strong&gt; class is &lt;strong&gt;OnModelCreating&lt;/strong&gt; which is using the Fluent API to configure and map database tables and columns with classes and properties. If you want Entity Framework to configure mappings using DataAnnotations then you can use the &lt;strong&gt;–DataAnnotations&lt;/strong&gt; parameter of &lt;strong&gt;Scaffold-DbContext&lt;/strong&gt; command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

    modelBuilder.Entity&amp;lt;Customer&amp;gt;(entity =&amp;gt;
    {
        entity.Property(e =&amp;gt; e.FirstName).IsRequired();

        entity.Property(e =&amp;gt; e.LastName).IsRequired();
    });

    ...

    OnModelCreatingPartial(modelBuilder);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Extending EF Core Generated DbContext Class
&lt;/h2&gt;

&lt;p&gt;In a real project, you would probably add more database tables or columns during development and every time you will generate model classes and DbContext class using Scaffold-DbContext, you will lose all your custom changes and configurations you have done in the OnModelCreating method. It is not recommended to add custom code in overridden method OnModelCreating and that’s why the Scaffold-DbContext command generates a partial method for us.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also see that this method is called from inside OnModelCreating method as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OnModelCreatingPartial(modelBuilder);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To extend generated DbContext class, you can create a partial class in your project with the same name and define your custom configurations inside the overridden OnModelCreatingPartial method. Add a file named &lt;strong&gt;_OnlineShopDbContext.cs&lt;/strong&gt; in the &lt;strong&gt;Data&lt;/strong&gt; folder and inside the file define the partial OnlineShopDbContext class by inheriting the same DbContext class. Inside OnModelCreatingPartial you can specify the custom configurations as shown in the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public partial class OnlineShopDbContext : DbContext
{
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&amp;lt;Customer&amp;gt;(entity =&amp;gt;
        {
            entity.Property(e =&amp;gt; e.Phone).IsRequired();
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Displaying Data in ASP.NET Core using EF Core
&lt;/h2&gt;

&lt;p&gt;In this final section of the tutorial, I will show you how you can use the generated OnlineShopDbContext in ASP.NET Core MVC to display data from the existing database. This is the same technique I have demonstrated in my previous tutorial &lt;a href="https://www.ezzylearning.net/tutorial/data-access-in-asp-net-core-using-ef-core-code-first"&gt;Data Access in ASP.NET Core using EF Core (Code First)&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First of all, we need to inject OnlineShopDbContext class in our HomeController constructor and then we can call the &lt;strong&gt;ToListAsync&lt;/strong&gt; method on &lt;strong&gt;Products&lt;/strong&gt; DbSet. This will automatically fetch data from the existing database. Once the data is available, we will pass the data to Razor View.&lt;br&gt;
&lt;br&gt;
  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HomeController : Controller
{
    private readonly OnlineShopDbContext _context;

    public HomeController(OnlineShopDbContext context)
    {
        _context = context;
    }

    public async Task&amp;lt;IActionResult&amp;gt; Index()
    {
        return View(await _context.Products.ToListAsync());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The Index Razor View declares the model as IEnumerable and then it has a standard &lt;strong&gt;foreach&lt;/strong&gt; loop that will iterate over the list of Products and will generate an HTML table on the page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@model IEnumerable&amp;lt;Product&amp;gt;

@{
    ViewData["Title"] = "Home Page";
}
&amp;lt;h2&amp;gt;Products&amp;lt;/h2&amp;gt;
&amp;lt;table class="table"&amp;gt;
    &amp;lt;thead&amp;gt;
        &amp;lt;tr&amp;gt;
            &amp;lt;th&amp;gt;
                @Html.DisplayNameFor(model =&amp;gt; model.Id)
            &amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;
                @Html.DisplayNameFor(model =&amp;gt; model.Name)
            &amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;
                @Html.DisplayNameFor(model =&amp;gt; model.Price)
            &amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;&amp;lt;/th&amp;gt;
        &amp;lt;/tr&amp;gt;
    &amp;lt;/thead&amp;gt;
    &amp;lt;tbody&amp;gt;
        @foreach (var item in Model)
        {
            &amp;lt;tr&amp;gt;
                &amp;lt;td&amp;gt;
                    @Html.DisplayFor(modelItem =&amp;gt; item.Id)
                &amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;
                    @Html.DisplayFor(modelItem =&amp;gt; item.Name)
                &amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;
                    @Html.DisplayFor(modelItem =&amp;gt; item.Price)
                &amp;lt;/td&amp;gt;
            &amp;lt;/tr&amp;gt;
        }
    &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you will run the project now, you will see the following page showing all the products from the database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PlCOdD5z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iy82oie83ugcdji8gg6e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PlCOdD5z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iy82oie83ugcdji8gg6e.png" alt="Products-Table-Data-Display-in-MVC-View-using-Entity-Framework-Core-Code-First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;In this tutorial, I have shown you how to generate model classes and DbContext from an existing database using Entity Framework commands and tools. I have also covered how to generate code with Fluent API or Data Annotations and finally, I gave you an example of extending the generated DbContext. If you like this post, please share it with your friends or colleagues to spread the knowledge further.&lt;/p&gt;

</description>
      <category>aspnetcore</category>
      <category>database</category>
      <category>entityframework</category>
      <category>efcore</category>
    </item>
    <item>
      <title>Data Access in ASP.NET Core using EF Core (Code First)</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Sun, 12 Sep 2021 17:47:04 +0000</pubDate>
      <link>https://dev.to/ezzylearning/data-access-in-asp-net-core-using-ef-core-code-first-1d30</link>
      <guid>https://dev.to/ezzylearning/data-access-in-asp-net-core-using-ef-core-code-first-1d30</guid>
      <description>&lt;p&gt;No matter, what type of application you are developing, it is most likely that your application needs some sort of data access for the purpose of reading and writing data to and from the database. Back in the day, the developers often used to write ADO.NET code to communicate with the database but in 2008, Microsoft introduced an ORM framework called Entity Framework to bridge the gap between the relational databases and object-oriented programming languages such as C#.  Entity Framework is still the most popular and widely used data access technology for .NET developers and its latest version is Entity Framework Core 5. In this tutorial, I will give you an overview of using Entity Framework Core 5 with ASP.NET Core 5 and we will focus on Code First technique that will allow you to create and manage database using code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/AspNetCoreEfCoreCodeFirstDemo"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction to Entity Framework Core
&lt;/h2&gt;

&lt;p&gt;Entity Framework (EF) Core is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology. Like other ORM frameworks, EF Core also enables .NET developers to work with a relational database using .NET classes and objects. Developers don’t need to worry about opening database connections, executing SQL commands or stored procedures, and so on. They can simply create and save objects to create rows in database tables and they can also run queries and fetch data from the database and load into .NET objects without writing any SQL queries ever.&lt;/p&gt;

&lt;h2&gt;
  
  
  Entity Framework Database Providers
&lt;/h2&gt;

&lt;p&gt;EF Core can access many different databases using database providers. There are providers available for almost all popular databases such as SQL Server, MySql, Oracle, PostgreSQL, etc. Some of these providers are maintained as part of the Entity Framework Core Project but others are available from third-party software vendors. Most of these database providers are available as NuGet packages and they are easy to install using the NuGet package manager. Make sure you review each provider's documentation for detailed information about configuring and using the provider.&lt;/p&gt;

&lt;p&gt;Following are some of the popular database providers for Entity Framework Core.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Data Provider&lt;/th&gt;
&lt;th&gt;Package&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;SQL Server 2012 onward&lt;/td&gt;
&lt;td&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer"&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SQLite&lt;/td&gt;
&lt;td&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite"&gt;Microsoft.EntityFrameworkCore.Sqlite&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;MySQL&lt;/td&gt;
&lt;td&gt;&lt;a href="https://www.nuget.org/packages/MySql.Data.EntityFrameworkCore"&gt;MySql.Data.EntityFrameworkCore&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Oracle &lt;/td&gt;
&lt;td&gt;&lt;a href="https://www.nuget.org/packages/Oracle.EntityFrameworkCore/"&gt;Oracle.EntityFrameworkCore&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Db2&lt;/td&gt;
&lt;td&gt;&lt;a href="https://www-112.ibm.com/software/howtobuy/passportadvantage/paocustomer/sdma/SDMA?P0=DOWNLOAD_SEARCH_BY_PART_NO&amp;amp;FIELD_SEARCH_TYPE=3&amp;amp;searchVal=CC6XFML"&gt;IBM.EntityFrameworkCore&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;If you want to learn how to use NuGet to download packages then read my post &lt;a href="https://www.ezzylearning.net/tutorial/working-with-packages-and-libraries-in-asp-net-core"&gt;Working with Packages and Libraries in ASP.NET Core&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Entity Model?
&lt;/h2&gt;

&lt;p&gt;Entity Framework supports data access using C# classes called data or entity models. These entity models are then used by a DbContext object that represents a session with the database. This DbContext object allows querying and saving data. There are different ways to create entity models in .NET projects.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Code First:&lt;/strong&gt; We can hand code a model as a C# class and then use &lt;a href="https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/"&gt;EF Migrations&lt;/a&gt; to create and update a database from the model. EF Migrations help us to create, update our database and keep the database synced with our model classes. This tutorial will cover this approach in detail.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Database First:&lt;/strong&gt; We can generate a model from an existing database. You can learn more about this approach in my other tutorial &lt;a href="https://dev.to/tutorial/data-access-in-asp-net-core-using-ef-core-database-first"&gt;Data Access in ASP.NET Core using EF Core (Database First)&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This article will help you to understand the Code First approach in an ASP.NET Core MVC application using Entity Framework Core migrations. We will create entities such as Product, Customer, Order, and ProductOrder and will create the following tables and relationships in the database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FgNUF3iY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kdi476gkriio2orzmpm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FgNUF3iY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kdi476gkriio2orzmpm.png" alt="Entity Framework Core Entity Model Db Design"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started with Entity Framework Core
&lt;/h2&gt;

&lt;p&gt;Let’s create a new ASP.NET MVC Web Application in Visual Studio 2019 using the File &amp;gt; New &amp;gt; Project menu. The first thing we need is to install Entity Framework Core and because we are using SQL Server database so we also need to install SQL Server Data Provider. Open the NuGet package manager and search for the following packages and install them in your project.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;NuGet Package&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/"&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;Microsoft SQL Server database provider for Entity Framework Core.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Design"&gt;Microsoft.EntityFrameworkCore.Design&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;This package has some shared design-time components for Entity Framework Core Tools&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/"&gt;Microsoft.EntityFrameworkCore.Tools&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;Entity Framework Core Tools will help us in running Migrations related commands e.g. Add-Migration, Remove-Migration, Update-Database directly from NuGet Package Manager Console in Visual Studio.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Product Model
&lt;/h3&gt;

&lt;p&gt;Next, we need to create our entity models and we normally put our models in the &lt;strong&gt;Models&lt;/strong&gt; folder by convention so let’s create a Models folder in the project root folder and create our first model class called &lt;strong&gt;Product&lt;/strong&gt; in it. I am adding the &lt;strong&gt;[Key]&lt;/strong&gt; attribute with the &lt;strong&gt;Id&lt;/strong&gt; property to make sure that the &lt;strong&gt;Id&lt;/strong&gt; column is defined as the primary key column of the table. The &lt;strong&gt;[Required]&lt;/strong&gt; attribute with the &lt;strong&gt;Name&lt;/strong&gt; property will make it a Non-Nullable column. Finally, we have a &lt;strong&gt;[Column]&lt;/strong&gt; attribute with the &lt;strong&gt;Price&lt;/strong&gt; property that specifies the data type and the length in the database to be 18 and 2 decimal point precision.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Product
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Column(TypeName = "decimal(18, 2)")]
    public decimal Price { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Customer Model
&lt;/h3&gt;

&lt;p&gt;Next, we need to create a Customer class that is slightly different than the Product class. We have basic properties such as Id, FirstName, LastName, etc., and a Navigation property &lt;strong&gt;Orders&lt;/strong&gt; which is a Collection of Order entities we will create shortly. When Entity Framework Core will generate database table Customers, it will automatically create a one to many relationships between the Customer and the Orders which means one customer can have many orders in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Customer
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string Phone { get; set; }

    public ICollection&amp;lt;Order&amp;gt; Orders { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Order Model
&lt;/h3&gt;

&lt;p&gt;Next, we need to create an Order entity that has some basic properties as well as a navigation property ProductOrders that will automatically generate an intersection table in the database for the &lt;strong&gt;Products&lt;/strong&gt; and &lt;strong&gt;Orders&lt;/strong&gt; table. The Order class also has another navigation property called &lt;strong&gt;Customer&lt;/strong&gt; that specifies that a customer can be associated with a single order. Note that I am also defining a &lt;strong&gt;CustomerId&lt;/strong&gt; property that will become the foreign key of &lt;strong&gt;Customer&lt;/strong&gt; table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Order
{
    [Key]
    public int Id { get; set; }

    public DateTime? OrderDate { get; set; }

    public int CustomerId { get; set; }

    public Customer Customer { get; set; }

    public ICollection&amp;lt;ProductOrder&amp;gt; ProductOrders { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  ProductOrder Model
&lt;/h3&gt;

&lt;p&gt;Finally, we need to create a ProductOrder entity that will map to our intersection table &lt;strong&gt;ProductOrders&lt;/strong&gt; in the database. There are two navigation properties &lt;strong&gt;Product&lt;/strong&gt; and &lt;strong&gt;Order&lt;/strong&gt; in this class along with two foreign key properties &lt;strong&gt;OrderId&lt;/strong&gt; and &lt;strong&gt;ProductId&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ProductOrder
{
    [Key]
    public int Id { get; set; }

    public int Quantity { get; set; }

    public int ProductId { get; set; }

    public int OrderId { get; set; }

    public Product Product { get; set; }

    public Order Order { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating Database Context in Entity Framework Core
&lt;/h2&gt;

&lt;p&gt;The &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext?view=efcore-2.0"&gt;&lt;strong&gt;DbContext&lt;/strong&gt;&lt;/a&gt; is the most important class of Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. It can be used to perform the following operations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Manage database connection&lt;/li&gt;
&lt;li&gt;Configure model &amp;amp; relationship&lt;/li&gt;
&lt;li&gt;Querying database&lt;/li&gt;
&lt;li&gt;Saving data to the database&lt;/li&gt;
&lt;li&gt;Configure change tracking&lt;/li&gt;
&lt;li&gt;Caching&lt;/li&gt;
&lt;li&gt;Transaction management&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s create a folder called &lt;strong&gt;Data&lt;/strong&gt; in our project and create a new class called &lt;strong&gt;OnlineShopDbContext&lt;/strong&gt; in this folder. We need to derive this class from the Entity Framework &lt;strong&gt;DbContext&lt;/strong&gt; class. Next, I created four properties of type &lt;strong&gt;DbSet&lt;/strong&gt; where each DbSet represents a table in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OnlineShopDbContext : DbContext
{
    public OnlineShopDbContext(DbContextOptions&amp;lt;OnlineShopDbContext&amp;gt; options) 
        : base(options)
    {

    }

    public DbSet&amp;lt;Product&amp;gt; Products { get; set; }
    public DbSet&amp;lt;Customer&amp;gt; Customers { get; set; }
    public DbSet&amp;lt;Order&amp;gt; Orders { get; set; }
    public DbSet&amp;lt;ProductOrder&amp;gt; ProductOrders { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to define our database connection string and we can save the connection string in the &lt;strong&gt;appsettings.json&lt;/strong&gt; file as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
   "ConnectionStrings":{
      "DefaultConnection":"Server=DESKTOP-6SDKTRC; Database=OnlineShopDb; Trusted_Connection=True; MultipleActiveResultSets=true"
   },
   "Logging":{
      "LogLevel":{
         "Default":"Information",
         "Microsoft":"Warning",
         "Microsoft.Hosting.Lifetime":"Information"
      }
   },
   "AllowedHosts":"*"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, we need to register the SQL Server database provider in &lt;strong&gt;Startup.cs&lt;/strong&gt; file using the &lt;strong&gt;UseSqlServer&lt;/strong&gt; method. The UseSqlServer method requires a database connection string and we can read and pass this information using the GetConnectionString method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDbContext&amp;lt;OnlineShopDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Using Entity Framework Core Migrations
&lt;/h2&gt;

&lt;p&gt;We have created entity models and DbContext object above so it is now time to generate our database with the help of migrations. Migrations allow us to easily create a new database and then incrementally update the database schema to keep it in sync with the application models. You can run migrations using &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/dotnet"&gt;.NET Core CLI tools&lt;/a&gt; which will work on all platforms but if you want to stay within Visual Studio then you can also use &lt;a href="https://docs.microsoft.com/en-us/ef/core/cli/powershell"&gt;Package Manager Console tools&lt;/a&gt;. For this tutorial, I will use Package Manager Console tools so let open Package Manager Console and add our first migration using the following &lt;strong&gt;Add-Migration&lt;/strong&gt; command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Add-Migration InitialDatabaseCreate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our first migration will be used to create a new SQL Server database that’s why I named it &lt;strong&gt;InitialDatabaseCreate&lt;/strong&gt; but you are free to use any name you want. Press Enter and you will see Build started and succeeded messages as follows.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--69MIjSYK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f90wmilyomajueo0wo8j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--69MIjSYK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f90wmilyomajueo0wo8j.png" alt="Add Migration Entity Framework Core - Code First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;EF Core will create a directory called &lt;strong&gt;Migrations&lt;/strong&gt; in the project and will also generate some files in this folder. Every time you will add a new migration using the Add-Migration command, a new file will be created in the Migrations folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TYjUviVm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kru1l4cujc84j8d57832.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TYjUviVm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kru1l4cujc84j8d57832.png" alt="View Entity Framework Core Migrations in Solution Explorer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you will open the generated file, you will see that the generated class InitialDatabaseCreate is derived from the Migration class, and two methods Up and Down are overridden in the class. The code inside these methods is self-explanatory. There are &lt;strong&gt;CreateTable&lt;/strong&gt; and &lt;strong&gt;CreateIndex&lt;/strong&gt; method calls in the &lt;strong&gt;Up&lt;/strong&gt; method and there are &lt;strong&gt;DropTable&lt;/strong&gt; calls in the &lt;strong&gt;Down&lt;/strong&gt; method. Up method upgrades our database from its current state to the new state expected by us. The Down method will do the reverse. It will revert our database to the state expected from the previous migration. We are free to add/update code in the files generated by migration commands such as Add-Migration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public partial class InitialDatabaseCreate : Migration
{
   protected override void Up(MigrationBuilder migrationBuilder)
   {
        migrationBuilder.CreateTable(
            name: "Customers",
            columns: table =&amp;gt; new
            {
                Id = table.Column&amp;lt;int&amp;gt;(type: "int", nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                FirstName = table.Column&amp;lt;string&amp;gt;(type: "nvarchar(max)", nullable: false),
                LastName = table.Column&amp;lt;string&amp;gt;(type: "nvarchar(max)", nullable: false),
                Phone = table.Column&amp;lt;string&amp;gt;(type: "nvarchar(max)", nullable: true)
            },
            constraints: table =&amp;gt;
            {
                table.PrimaryKey("PK_Customers", x =&amp;gt; x.Id);
            });

       ...
       ...
   }

   protected override void Down(MigrationBuilder migrationBuilder)
   {
        ...
        ...
        migrationBuilder.DropTable(name: "Customers");
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are now ready to create our database and tables using the migration code generated for us. This can be done by running Update-Database command in Package Manager Console within Visual Studio.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Update-Database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s take a look at the database and tables created automatically for us without writing a single line of SQL. Open SQL Server database and you will see a new database &lt;strong&gt;OnlineShopDb&lt;/strong&gt; is now available in the list of Databases. If you will expand the Tables node, you will also see that the Products, Orders, etc. tables are created for us.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--s-2TWEie--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwkbhf13ywvf3vh5v4pg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--s-2TWEie--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwkbhf13ywvf3vh5v4pg.png" alt="Update Database Entity Framework Core - Code First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you will open the Products table design view, then you will see the table has the same fields and data types we specified in our Product model above.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Yi4aM5vP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zmmqhzva77m1l1ib2fjv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Yi4aM5vP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zmmqhzva77m1l1ib2fjv.png" alt="Products Table Generated using Entity Framework Core Code First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now open the Customer table and you will notice that it is also created exactly how we expected.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--z8te9Fiz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kf7jbpoxkkggvb7d96mn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--z8te9Fiz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kf7jbpoxkkggvb7d96mn.png" alt="Customers Table Generated using Entity Framework Core Code First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You may be wondering from where that &lt;strong&gt;__EFMigrationsHistory&lt;/strong&gt; table came from because we haven’t created any model for this table. This table is a special table, auto created by Entity Framework to keep track of all the migrations already ran against the database. If you will open the table, you will see that it has our first migration &lt;strong&gt;InitialDatabaseCreate&lt;/strong&gt; entry saved in it. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JfZnuV8Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jjyii2mj3xv7drku9yc3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JfZnuV8Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jjyii2mj3xv7drku9yc3.png" alt="Initial Database Create Migration in Entity Framework Core"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s say you have a new requirement and you want to save customer Emails in the database. You first need to create a new property &lt;strong&gt;Email&lt;/strong&gt; in the &lt;strong&gt;Customer&lt;/strong&gt; model class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Customer
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string Phone { get; set; }

    public string Email { get; set; }

    public ICollection&amp;lt;Order&amp;gt; Orders { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, you need to add a new migration to sync your model with the database. I have given it the name &lt;strong&gt;AddEmailInCustomers.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Add-Migration AddEmailInCustomers
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Entity Framework will generate another class in the &lt;strong&gt;Migrations&lt;/strong&gt; folder for our migration and you can update your database using the same Update-Database command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Update-Database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Go to database and open the &lt;strong&gt;Customers&lt;/strong&gt; table in design view and you will see a new column &lt;strong&gt;Email&lt;/strong&gt; added in the table as expected. A new migration entry will also be added in &lt;strong&gt;__EFMigrationsHistory&lt;/strong&gt; table.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LYIOrDr3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bldgdw1gzbist2dy4sme.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LYIOrDr3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bldgdw1gzbist2dy4sme.png" alt="Customers Table Generated using Entity Framework Core Code First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Seeding Data using EF Core Migrations
&lt;/h2&gt;

&lt;p&gt;So far, we have learned how to create database and tables using EF Migrations and how to keep our database synched with the entity model. Now, let’s say you want to add some initial data in the Products table. You can do this easily by overriding the &lt;strong&gt;OnModelCreating&lt;/strong&gt; method of &lt;strong&gt;DbContext&lt;/strong&gt; in our project &lt;strong&gt;OnlineShopDbContext&lt;/strong&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OnlineShopDbContext : DbContext
{
    public OnlineShopDbContext(DbContextOptions&amp;lt;OnlineShopDbContext&amp;gt; options) 
        : base(options)
    {
    }

    public DbSet&amp;lt;Product&amp;gt; Products { get; set; }
    public DbSet&amp;lt;Customer&amp;gt; Customers { get; set; }
    public DbSet&amp;lt;Order&amp;gt; Orders { get; set; }
    public DbSet&amp;lt;ProductOrder&amp;gt; ProductOrders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&amp;lt;Product&amp;gt;().HasData(
            new Product() { Id = 1, Name = "Apple iPad", Price = 1000 },
            new Product() { Id = 2, Name = "Samsung Smart TV", Price = 1500 },
            new Product() { Id = 3, Name = "Nokia 130", Price = 1200 });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We want to see some products in the Products table that’s why I am adding the migration with &lt;strong&gt;SeedProductsData&lt;/strong&gt; name&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Add-Migration SeedProductsData
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As soon as the above command will execute, a new migration class will be added in the &lt;strong&gt;Migrations&lt;/strong&gt; folder and if you will open the class you will see code similar to the following. You can see how the code is calling the &lt;strong&gt;InsertData&lt;/strong&gt; method of &lt;strong&gt;MigrationBuilder&lt;/strong&gt; class add adding the same data we seeded above in the &lt;strong&gt;Products&lt;/strong&gt; table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public partial class SeedProductsData : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.InsertData(
            table: "Products",
            columns: new[] { "Id", "Name", "Price" },
            values: new object[] { 1, "Apple iPad", 1000m });

        migrationBuilder.InsertData(
            table: "Products",
            columns: new[] { "Id", "Name", "Price" },
            values: new object[] { 2, "Samsung Smart TV", 1500m });

        migrationBuilder.InsertData(
            table: "Products",
            columns: new[] { "Id", "Name", "Price" },
            values: new object[] { 3, "Nokia 130", 1200m });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, run the Update-Database command and then open the Products table&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OwAMdX5G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ute9dzhoq9cutqyiq8dl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OwAMdX5G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ute9dzhoq9cutqyiq8dl.png" alt="Products Table Data with Seeding in Entity Framework Core Code First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Displaying Data in ASP.NET Core using EF Core
&lt;/h2&gt;

&lt;p&gt;In this final section of the tutorial, I will show you how you can use the Entity Framework Core in ASP.NET Core MVC to display data from the database. First of all, we need to inject OnlineShopDbContext class in our HomeController constructor and then we can simply call the &lt;strong&gt;ToListAsync&lt;/strong&gt; method on &lt;strong&gt;Products&lt;/strong&gt; DbSet as shown below. This will automatically fetch data from the database and we are then returning the data to Razor View.&lt;br&gt;
&lt;br&gt;
   &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HomeController : Controller
{
    private readonly OnlineShopDbContext _context;

    public HomeController(OnlineShopDbContext context)
    {
        _context = context;
    }

    public async Task&amp;lt;IActionResult&amp;gt; Index()
    {
        return View(await _context.Products.ToListAsync());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The Index Razor View will first declare the model as IEnumerable because our Home Controller is passing a list of products to our Razor View. Finally, I have a standard &lt;strong&gt;foreach&lt;/strong&gt; loop that will iterate over the list of Products and will generate an HTML table on the page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@model IEnumerable&amp;lt;Product&amp;gt;

@{
    ViewData["Title"] = "Home Page";
}
&amp;lt;h2&amp;gt;Products&amp;lt;/h2&amp;gt;
&amp;lt;table class="table"&amp;gt;
    &amp;lt;thead&amp;gt;
        &amp;lt;tr&amp;gt;
            &amp;lt;th&amp;gt;
                @Html.DisplayNameFor(model =&amp;gt; model.Id)
            &amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;
                @Html.DisplayNameFor(model =&amp;gt; model.Name)
            &amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;
                @Html.DisplayNameFor(model =&amp;gt; model.Price)
            &amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;&amp;lt;/th&amp;gt;
        &amp;lt;/tr&amp;gt;
    &amp;lt;/thead&amp;gt;
    &amp;lt;tbody&amp;gt;
        @foreach (var item in Model)
        {
            &amp;lt;tr&amp;gt;
                &amp;lt;td&amp;gt;
                    @Html.DisplayFor(modelItem =&amp;gt; item.Id)
                &amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;
                    @Html.DisplayFor(modelItem =&amp;gt; item.Name)
                &amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;
                    @Html.DisplayFor(modelItem =&amp;gt; item.Price)
                &amp;lt;/td&amp;gt;
            &amp;lt;/tr&amp;gt;
        }
    &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you will run the project now, you will see the following page showing all the products from the database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7juPXjGM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sr7nsi6c2hm4mwy59e0f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7juPXjGM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sr7nsi6c2hm4mwy59e0f.png" alt="Products Table Data Display in MVC View using Entity Framework Core Code First"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;In this tutorial, I have covered the basics of Entity Framework Core and gave you an overview of Entity Models. I have also covered how to use Entity Framework Code First technique to create a database from scratch using EF Core Migrations. I hope this tutorial will help you at your work or in your projects. Please leave your comments so that I can improve my posts based on your feedback. If you like this post, please share it with your friends or colleagues to spread the knowledge further.&lt;/p&gt;

</description>
      <category>aspnetcore</category>
      <category>database</category>
      <category>entityframework</category>
      <category>codefirst</category>
    </item>
    <item>
      <title>ASP.NET Core Bundling and Minification Using Gulp</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Sun, 29 Aug 2021 09:39:11 +0000</pubDate>
      <link>https://dev.to/ezzylearning/asp-net-core-bundling-and-minification-using-gulp-27m8</link>
      <guid>https://dev.to/ezzylearning/asp-net-core-bundling-and-minification-using-gulp-27m8</guid>
      <description>&lt;p&gt;In my previous post &lt;a href="https://www.ezzylearning.net/tutorial/a-step-by-step-guide-to-bundling-and-minification-in-asp-net-core" rel="noopener noreferrer"&gt;A Step by Step Guide to Bundling and Minification in ASP.NET Core&lt;/a&gt;, I gave you an overview of the different tools and strategies we can use to implement bundling and minification in ASP.NET Core. I also covered the Visual Studio extension called &lt;a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BundlerMinifier" rel="noopener noreferrer"&gt;Bundler &amp;amp; Minifier&lt;/a&gt;. These basic tools and extensions are only useful for basic workflows and if your requirements are more complex or you need more than bundling and minification or you want to automate some of these tasks to make your life easier then you have to use task runners such as Gulp, Grunt or Webpack. In this tutorial, I will show you how to use Gulp in Visual Studio and how to use Gulp tasks to automate bundling and minification in Visual Studio.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/AspNetCoreBundlingWithGulpDemo" rel="noopener noreferrer"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What is Gulp?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://gulpjs.com/" rel="noopener noreferrer"&gt;Gulp&lt;/a&gt; is one of the most popular and cross-platform streaming task runners that provide you all the tools and plugins to automate slow and repetitive development routines and workflows and compose them into efficient build pipelines. At a high level, gulp reads files as streams and pipes these streams to different tasks. The main part of the development with gulp is creating tasks using JavaScript. These tasks can use thousands of npm packages to perform different tasks. There are also other popular task runners such as Grunt and Webpack and Visual Studio has native support for these task runners. In this tutorial, we will use the latest version of Gulp 4.0 that is rewritten from the ground-up and will allow us to compose tasks using new &lt;strong&gt;series()&lt;/strong&gt; and &lt;strong&gt;parallel()&lt;/strong&gt; methods. There are also many more advancements added in version 4.0 and you can read about all the new features &lt;a href="https://github.com/gulpjs/gulp" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjww47yvu5peso6wzqkdd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjww47yvu5peso6wzqkdd.png" alt="Understanding Gulp Tasks Pipeline"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The gulp tasks we needed to perform bundling and minification are as follows:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We need a gulp task that will delete existing bundled or minified files.&lt;/li&gt;
&lt;li&gt;We need a gulp task that will read JavaScript files from a source folder and will bundle them together, minifies the bundled file, and finally save it to a target folder.&lt;/li&gt;
&lt;li&gt;We need a gulp task that will read CSS files from a source folder and will bundle them together, minifies the bundled file, and finally save it to a target folder.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will use the following plugins to perform the above tasks.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/del" rel="noopener noreferrer"&gt;del&lt;/a&gt; – Deletes files and directories&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/gulp-concat" rel="noopener noreferrer"&gt;gulp-concat&lt;/a&gt; – Concatenates files&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/gulp-cssmin" rel="noopener noreferrer"&gt;gulp-cssmin&lt;/a&gt; – Minifies CSS files&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/gulp-uglify" rel="noopener noreferrer"&gt;gulp-uglify&lt;/a&gt; – Minifies JavaScript files&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/merge-stream" rel="noopener noreferrer"&gt;merge-streams&lt;/a&gt; – Merges multiple streams&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are thousands of plugins available to perform all types of routine tasks using gulp. You can search these plugins in &lt;a href="https://www.npmjs.com" rel="noopener noreferrer"&gt;npm packages repository&lt;/a&gt;. If you are not comfortable in using client-side packages and libraries, I will recommend you read my post &lt;a href="https://www.ezzylearning.net/tutorial/working-with-packages-and-libraries-in-asp-net-core" rel="noopener noreferrer"&gt;Working with Packages and Libraries in ASP.NET Core&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What is Gulpfile.js&lt;/strong&gt;?
&lt;/h2&gt;

&lt;p&gt;So far, we have learned that we need to define gulp tasks using JavaScript and we have to use different plugins to perform different routine tasks now the last question is where we will define these tasks. This is where &lt;strong&gt;Gulpfile.js&lt;/strong&gt; comes in. A Gulpfile.js or gulpfile.js is a file in your project directory that automatically loads when we run the &lt;strong&gt;gulp&lt;/strong&gt; command. In this file, we often define tasks and use gulp APIs like src(), dest(), series(), parallel() etc. We will also create this file shortly to define our gulp tasks. You can read more about this file &lt;a href="https://gulpjs.com/docs/en/getting-started/javascript-and-gulpfiles/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Converting bundleconfig.json to Gulp&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In my last tutorial &lt;a href="https://www.ezzylearning.net/tutorial/a-step-by-step-guide-to-bundling-and-minification-in-asp-net-core" rel="noopener noreferrer"&gt;A Step by Step Guide to Bundling and Minification in ASP.NET Core&lt;/a&gt;, we created a bundleconfig.json file for bundling and minification and we also installed a Visual Studio extension called &lt;strong&gt;&lt;a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BundlerMinifier" rel="noopener noreferrer"&gt;BundlerMinifier&lt;/a&gt;&lt;/strong&gt;. We can reuse the same bundleconfig.json file from Gulp but you have to remove some extra options from the bundleconfig.json file. The following bundleconfig.json file is a trim down version we need in this tutorial. It is simply defining some CSS and JavaScript bundles with source and destination paths.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
   {
      "outputFileName":"wwwroot/css/main.min.css",
      "inputFiles":[
         "wwwroot/lib/bootstrap/dist/css/bootstrap.css",
         "wwwroot/css/site.css"
      ]
   },
   {
      "outputFileName":"wwwroot/js/main.min.js",
      "inputFiles":[
         "wwwroot/lib/jquery/dist/jquery.js",
         "wwwroot/lib/bootstrap/dist/js/bootstrap.js",
         "wwwroot/js/site.js"
      ]
   }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first step to start using Gulp in your ASP.NET Core project is to install Gulp and related npm modules and create a Gulpfile.js. We can do all this easily by using Bundler &amp;amp; Minifier "&lt;strong&gt;Convert To Gulp&lt;/strong&gt;" option. Right-click on the bundleconfig.json file, choose Bundler &amp;amp; Minifier, and then choose "Convert To Gulp…" option from the menu as shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr7s3pzi1iac45udx5plu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr7s3pzi1iac45udx5plu.png" alt="Convert to Gulp using Bundler and Minifier"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You will see the following confirmation message asking you about generating gulpfile.js and installing npm packages. You can press OK to proceed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj660qbk2lv41xunn029h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj660qbk2lv41xunn029h.png" alt="Warning to Install Gulp File and NPM Packages"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After few minutes of downloading, you will see the following new items in your solution explorer.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A gulpfile.js&lt;/li&gt;
&lt;li&gt;A package.json&lt;/li&gt;
&lt;li&gt;Some npm packages are added in Dependencies&lt;/li&gt;
&lt;li&gt;A node_modules folder is added in which many node packages are downloaded and installed&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxjxbsxmerathed8rov3a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxjxbsxmerathed8rov3a.png" alt="NPM Packages and Node Modules Installed in Project"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A package.json file is a JSON file that is normally available at the root of a project and it contains the metadata information related to the project. It is used to manage the project’s dependencies, scripts, versions, etc. If you will open the generated package.json file you will notice that it has project name, version, and some development related dependencies which are mainly npm packages we will use in gulpfile.js file shortly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
   "name":"AspNetCoreBundlingWithGulpDemo",
   "version":"1.0.0",
   "private":true,
   "devDependencies":{
      "del":"^6.0.0",
      "gulp":"^4.0.2",
      "gulp-concat":"^2.6.1",
      "gulp-cssmin":"^0.2.0",
      "gulp-uglify":"^3.0.2",
      "merge-stream":"^2.0.0"
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;How to Define Tasks in Gulp&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If you will open gulpfile.js, you will notice that the Bundler &amp;amp; Minifier extension has already generated all the gulp tasks for you. The problem with this generated code is that it is not using Gulp 4.0 even though the package.json file is showing gulp version 4.0.2 in it. This means you have two options now.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;You can downgrade your Gulp version in package.json and continue using the generated gulp tasks available in gulpfile.js file&lt;/li&gt;
&lt;li&gt;You can use the latest Gulp version 4.0.2 and update gulpfile.js code to use the latest Gulp features.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I have chosen option 2 above as it's always a good option to use the latest version of any tool or framework.&lt;/p&gt;

&lt;p&gt;It is now time to update gulpfile.js and learn more about gulp. First of all, we need to specify/import all the required npm packages. These packages can be loaded either by path or name and each of them will be assigned to a variable. This is similar to importing NuGet packages in C# files while working on the server-side.&lt;/p&gt;

&lt;p&gt;We are loading the main ‘&lt;strong&gt;gulp&lt;/strong&gt;’ package that contains all gulp related methods and features. Next, we are loading all npm packages I mentioned at the start of this tutorial. Finally, we are saving the reference of bundleconfig.json file in a local variable bundleconfig so that we can read input and output file paths from bundleconfig.json file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var gulp = require("gulp"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    merge = require("merge-stream"),
    del = require("del"),
    bundleconfig = require("./bundleconfig.json");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we have a regex variable that will keep both css and js files regex which are used in &lt;strong&gt;getBundles&lt;/strong&gt; function to filter and fetch files matching with a specific regex pattern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var regex = {
    css: /\\.css$/,
    js: /\\.js$/
};

function getBundles(regexPattern) {
    return bundleconfig.filter(function (bundle) {
        return regexPattern.test(bundle.outputFileName);
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Clean Task&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Next, we need to define the ‘&lt;strong&gt;clean&lt;/strong&gt;’ gulp task. The clean task will remove the existing minified files so that they can be regenerated with the updated code or functionality. Notice that the gulp tasks are simply JavaScript functions. We create JavaScript functions and then registered them by using &lt;strong&gt;gulp.task()&lt;/strong&gt; method as we did with our clean function below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function clean() {
    var files = bundleconfig.map(function (bundle) {
        return bundle.outputFileName;
    });

    return del(files);
}
gulp.task(clean);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Minify JS Task&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;To minify JavaScript files, I am creating minJs task. This task&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Load all JavaScript files&lt;/li&gt;
&lt;li&gt;Concatenates or bundle all files using ‘&lt;strong&gt;concat&lt;/strong&gt;’ module&lt;/li&gt;
&lt;li&gt;Minify the bundled file using ‘&lt;strong&gt;ugligy&lt;/strong&gt;’ module&lt;/li&gt;
&lt;li&gt;Place the resulting minified file at the root location
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function minJs() {
    var tasks = getBundles(regex.js).map(function (bundle) {
        return gulp.src(bundle.inputFiles, { base: "." })
            .pipe(concat(bundle.outputFileName))
            .pipe(uglify())
            .pipe(gulp.dest("."));
    });
    return merge(tasks);
}
gulp.task(minJs);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Minify CSS Task&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;To minify CSS files, I am creating minCss task. This task&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Load all CSS files&lt;/li&gt;
&lt;li&gt;Concatenates or bundle all files using ‘&lt;strong&gt;concat&lt;/strong&gt;’ module&lt;/li&gt;
&lt;li&gt;Minify the bundled file using '&lt;strong&gt;cssmin&lt;/strong&gt;' module&lt;/li&gt;
&lt;li&gt;Place the resulting minified file at the root location
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function minCss() {
    var tasks = getBundles(regex.css).map(function (bundle) {
        return gulp.src(bundle.inputFiles, { base: "." })
            .pipe(concat(bundle.outputFileName))
            .pipe(cssmin())
            .pipe(gulp.dest("."));
    });
    return merge(tasks);
}
gulp.task(minCss);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the end, I created a named task with the name ‘min’ and combine all task functions using gulp.series() method. The &lt;strong&gt;gulp.series()&lt;/strong&gt; method executes multiple tasks one after another in a series. There is also another method called &lt;strong&gt;gulp.parallel()&lt;/strong&gt; that can be used to execute multiple tasks simultaneously.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;gulp.task("min", gulp.series(clean, minJs, minCss));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Following is the complete gulpfile.js file with all the tasks&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use strict";

var gulp = require("gulp"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    merge = require("merge-stream"),
    del = require("del"),
    bundleconfig = require("./bundleconfig.json");

var regex = {
    css: /\\.css$/,
    js: /\\.js$/
};

function getBundles(regexPattern) {
    return bundleconfig.filter(function (bundle) {
        return regexPattern.test(bundle.outputFileName);
    });
}

function clean() {
    var files = bundleconfig.map(function (bundle) {
        return bundle.outputFileName;
    });

    return del(files);
}
gulp.task(clean);

function minJs() {
    var tasks = getBundles(regex.js).map(function (bundle) {
        return gulp.src(bundle.inputFiles, { base: "." })
            .pipe(concat(bundle.outputFileName))
            .pipe(uglify())
            .pipe(gulp.dest("."));
    });
    return merge(tasks);
}
gulp.task(minJs);

function minCss() {
    var tasks = getBundles(regex.css).map(function (bundle) {
        return gulp.src(bundle.inputFiles, { base: "." })
            .pipe(concat(bundle.outputFileName))
            .pipe(cssmin())
            .pipe(gulp.dest("."));
    });
    return merge(tasks);
}
gulp.task(minCss);

gulp.task("min", gulp.series(clean, minJs, minCss));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Running Gulp Tasks in Visual Studio&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;We are now ready to run our gulp tasks using Visual Studio. Open the Task Runner Explorer window and you will notice that it is reading Gulpfile.js and showing all gulp tasks. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg85w1ywoqi5dts9lfztd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg85w1ywoqi5dts9lfztd.png" alt="Gulp File and Tasks in Task Runner Explorer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can run the ‘&lt;strong&gt;min&lt;/strong&gt;’ task by right-clicking it and selecting "&lt;strong&gt;Run&lt;/strong&gt;". The ‘min’ task will be shown on the right-hand side and you can also view the logs which display when a particular task is finished and how much time a particular task took to complete.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl10spw7t87d42y3ccy7k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl10spw7t87d42y3ccy7k.png" alt="Run Gulp Tasks in Visual Studio Task Runner Explorer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You will see that the &lt;strong&gt;main.min.css&lt;/strong&gt; and &lt;strong&gt;main.min.js&lt;/strong&gt; files will be generated in Solution Explorer. You can also run individual tasks to perform a specific function. For example, you can run the ‘clean’ task to delete the minified files.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frl9m7z9wdd3zd6gc0wb9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frl9m7z9wdd3zd6gc0wb9.png" alt="Minified Files Generated using Gulp Tasks"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Binding Gulp Tasks with Visual Studio Events&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Running gulp tasks from Task Runner Explorer every time you make some changes in JavaScript of CSS files during development seems a non-productive method. You can automate this process by binding these tasks with certain Visual Studio events. You can&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Bind any task with any event&lt;/li&gt;
&lt;li&gt;Bind one task with multiple events&lt;/li&gt;
&lt;li&gt;Bind multiple tasks with a single event&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We can bind Gulp.js tasks with the following Visual Studio events:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Before Build&lt;/li&gt;
&lt;li&gt;After Build&lt;/li&gt;
&lt;li&gt;Clean Build&lt;/li&gt;
&lt;li&gt;Project Open&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To bind a task with an event, right-click on a task in Task Runner Explorer and choose any event from the child menu of the “&lt;strong&gt;Bindings&lt;/strong&gt;” menu as shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F98j9n2yt9exnbnhf3sk1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F98j9n2yt9exnbnhf3sk1.png" alt="Binding Gulp Tasks with Visual Studio Events"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can also define this binding directly in the gulpfile.js using the following syntax. The following line states that the '&lt;strong&gt;min&lt;/strong&gt;’ task should run when Visual Studio executes the &lt;strong&gt;AfterBuild&lt;/strong&gt; event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/// &amp;lt;binding AfterBuild='min' /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Summary&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In this tutorial, I have shown you how to write and integrate Gulp tasks in Visual Studio to manage the Bundling and Minification of JavaScript and CSS files automatically. You can create all sorts of tasks by using thousands of modules available in the online npm repository. I hope you have learned something new in this tutorial and you will start doing more and more automation to make yourself more productive as a developer.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>aspnetcore</category>
      <category>bundling</category>
      <category>gulp</category>
    </item>
    <item>
      <title>7 Productivity Tips for Developers (Infographic)</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Sun, 29 Aug 2021 09:28:56 +0000</pubDate>
      <link>https://dev.to/ezzylearning/7-productivity-tips-for-developers-infographic-26mf</link>
      <guid>https://dev.to/ezzylearning/7-productivity-tips-for-developers-infographic-26mf</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fft53zl5cys52mrgyotlk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fft53zl5cys52mrgyotlk.png" alt="7 Productivity Tips for Developers (Infographic)"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>developers</category>
      <category>infograpics</category>
      <category>tips</category>
    </item>
    <item>
      <title>A Step by Step Guide to Bundling and Minification in ASP.NET Core</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Sun, 29 Aug 2021 09:26:02 +0000</pubDate>
      <link>https://dev.to/ezzylearning/a-step-by-step-guide-to-bundling-and-minification-in-asp-net-core-2b44</link>
      <guid>https://dev.to/ezzylearning/a-step-by-step-guide-to-bundling-and-minification-in-asp-net-core-2b44</guid>
      <description>&lt;p&gt;It is the dream of every web developer to build blazing fast and high-performance web applications but this is not easy to accomplish unless we implement some performance optimizations. Web pages have evolved from static HTML pages to complex and responsive pages with a lot of dynamic contents and plugins which require a large number of CSS and JavaScript files to be downloaded to the clients. To improve the initial page request load time, we normally apply two performance techniques called bundling and minification. In this tutorial, I will give you a step by step overview of different tools and techniques we can use to apply bundling and minification in ASP.NET Core 5 applications.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/AspNetCoreBundleMinifyDemo" rel="noopener noreferrer"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction To Bundling and Minification
&lt;/h2&gt;

&lt;p&gt;Bundling and minification are two distinct performance optimizations we can use in our web apps to improve the performance of our apps and to reduce the number of requests from the browser to server and to reduce the size of data transferred from server to browser. If these two techniques are used together they improve the load time of our page on the first request. Once the page has been requested and loaded into the browser, the browser caches the static files e.g. JavaScript, CSS, and images so this improves the overall user experience.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bundling
&lt;/h2&gt;

&lt;p&gt;Bundling is a process of combining multiple files into a single file. The benefit is that the browser needs to make fewer requests for all those separate files and needs to load just a single file from the server. We can have separate bundles for CSS and JavaScript files and we can even have separate bundles for third-party plugins, scripts, and styles.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9yd7wf7k9qq5y1ffxyz3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9yd7wf7k9qq5y1ffxyz3.png" alt="ASP.NET Core Bundling"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Minification
&lt;/h2&gt;

&lt;p&gt;Minification is the process of removing unnecessary comments, spaces, and extra characters from the code without altering any functionality. This means we can reduce the file size significantly which increases the file load time from server to client.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4d28md0n6bo2e4i13x16.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4d28md0n6bo2e4i13x16.png" alt="ASP.NET Core Minification"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The following table (&lt;a href="https://docs.microsoft.com/en-us/aspnet/core/client-side/bundling-and-minification?view=aspnetcore-5.0" rel="noopener noreferrer"&gt;available at the official docs page&lt;/a&gt;) outlines the differences between individually loading assets and using bundling and minification on a local machine. You can expect even greater performance gains when bundled and minified assets are transferred over the network.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Action&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;With&lt;br&gt;Bundling and Minification&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Without&lt;br&gt;Bundling and Minification&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Change&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;File Requests&lt;/td&gt;
&lt;td&gt;7&lt;/td&gt;
&lt;td&gt;18&lt;/td&gt;
&lt;td&gt;157%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;KB Transferred&lt;/td&gt;
&lt;td&gt;156&lt;/td&gt;
&lt;td&gt;264.68&lt;/td&gt;
&lt;td&gt;70%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Load Time (ms)&lt;/td&gt;
&lt;td&gt;885&lt;/td&gt;
&lt;td&gt;2360&lt;/td&gt;
&lt;td&gt;167%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Bundling and Minification Strategies in ASP.NET Core
&lt;/h2&gt;

&lt;p&gt;In old days, we were using a different technique to register all our bundles in &lt;strong&gt;BundleConfig.cs&lt;/strong&gt; file available in &lt;strong&gt;App_Start&lt;/strong&gt; folder. A method called &lt;strong&gt;RegisterBundles&lt;/strong&gt; in ASP.NET was used to create, register, and configure bundles as follows:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public static void RegisterBundles(BundleCollection bundles)
{   
    bundles.Add(new ScriptBundle("~/bundles/js").Include(
      "~/Scripts/bootstrap.js",
      "~/Scripts/jquery-3.3.1.js"));
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We were including above bundles in our Web pages, Views and Layout Pages as follows:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;@ViewBag.Title&amp;lt;/title&amp;gt;

    @Scripts.Render("~/bundles/js")
&amp;lt;/head&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;While this approach looks easy to use, it’s no longer applicable in ASP.NET 5. The new ASP.NET Core project templates in Visual Studio provide a solution for bundling and minification using a JSON configuration file called &lt;strong&gt;bundleconfig.json&lt;/strong&gt;. There are also some NuGet Packages and Visual Studio extensions that can help us in bundling and minification. If you need a more advanced bundling and minification solution or your workflow requires processing beyond bundling and minification then you have the option of using third-party tools or task runners such as Gulp, Grunt or Webpack, etc.&lt;/p&gt;

&lt;p&gt;Another important aspect is to decide whether you want to do bundling and minification at design time or run time. Design time bundling and minification will allow you to create minified files before application deployment which will reduce server load time. However, the downside is that the design time bundling and minification only work with static files and it will also increase the build complexity.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Configure Bundles using bundleconfig.json File&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In ASP.NET Core we typically add our static files in the &lt;strong&gt;wwwroot&lt;/strong&gt; folder. There is a folder &lt;strong&gt;css&lt;/strong&gt; for CSS files, a folder &lt;strong&gt;js&lt;/strong&gt; for JavaScript files, and a third folder &lt;strong&gt;lib&lt;/strong&gt; for external libraries such as JQuery, bootstrap, etc. To start bundling and minification, the first you need is a &lt;strong&gt;bundleconfig.json&lt;/strong&gt; file so let’s add this file using the standard Add New Item dialog in Visual Studio.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbbj8ym17hwb8r1nztzag.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbbj8ym17hwb8r1nztzag.png" alt="Add bundleconfig JSON file in Visual Studio 2019"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Typically, we add this file to our project root folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3mwr8ysiz643za8e72h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3mwr8ysiz643za8e72h.png" alt="Solution Explorer with bundleconfig JSON file"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here's an example of how the contents of &lt;strong&gt;bundleconfig.json&lt;/strong&gt; look like in the default template:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    "inputFiles": [
      "wwwroot/lib/bootstrap/dist/css/bootstrap.css",
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "sourceMap": false
  }
]


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It is not very difficult to understand the JSON available in the bundleconfig.json file. There is a JSON object for each bundle we want to configure and there are some options available related to each bundle e.g. &lt;strong&gt;outputFileName&lt;/strong&gt;, &lt;strong&gt;inputFiles&lt;/strong&gt; etc. The default template has a single bundle configuration for custom JavaScript &lt;strong&gt;wwwroot/js/site.js&lt;/strong&gt; and a single bundle configuration for custom stylesheet &lt;strong&gt;wwwroot/css/site.css&lt;/strong&gt; files.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
    "outputFileName": "wwwroot/css/site.min.css",
    "inputFiles": [
      "wwwroot/lib/bootstrap/dist/css/bootstrap.css",
      "wwwroot/css/site.css"
    ]
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Some of the common options available are the following:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;outputFileName:&lt;/strong&gt; This is a required option and this specifies the name of the output bundle file. It can contain a relative path from the bundleconfig.json file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;inputFiles&lt;/strong&gt;: This is an array of files we want to bundle together and it can also contain relative paths from the bundleconfig.json file. This option is not required so if you will not specify any input file, an empty output file will be generated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;minify&lt;/strong&gt;: This is another optional setting and it specifies whether we want to enable minification or not. The default value is enabled: true.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;sourceMap&lt;/strong&gt;: This option indicates whether a source map for the bundled file should be generated or not. The default value is false.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;includeInProject&lt;/strong&gt;: This option specifies whether to add generated files to the project file. The default value is false. Let’s modify the default template and include both bootstrap and jquery into the generated bundle files. I have also renamed the output file name from &lt;strong&gt;site&lt;/strong&gt; to &lt;strong&gt;main&lt;/strong&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

[
  {
    "outputFileName": "wwwroot/css/main.min.css",
    "inputFiles": [
      "wwwroot/lib/bootstrap/dist/css/bootstrap.css",
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/main.min.js",
    "inputFiles": [
      "wwwroot/lib/jquery/dist/jquery.js",
      "wwwroot/lib/bootstrap/dist/js/bootstrap.js",
      "wwwroot/js/site.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "sourceMap": false
  }
]


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Bundling and Minification using BuildBundlerMinifier Package&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In the previous section, we added the bundleconfig.json file and configure our bundles in this JSON file. If you will build your project in Visual Studio, nothing will happen and no bundles will be generated. This is because you need to install a NuGet package called BuildBundlerMinifier to let Visual Studio and .NET know that they need to build your bundles. You can install this package from the NuGet package manager available within Visual Studio.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3c8yvxiayxzut2tbcrbk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3c8yvxiayxzut2tbcrbk.png" alt="Install BuildBundleMinifier Nuget Package"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once the package is installed, build your project and you will now see your bundled and minified files generated in the folder specified in bundleconfig.json. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fprzrzyqw7n52me27lvph.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fprzrzyqw7n52me27lvph.png" alt="Solution Explorer showing Minified JS and CSS files"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Environment-based Bundling and Minification&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;I am sure you would like to use the non-bundles and non-minified files in the development environment because they will make your life much easier during debugging. As a best practice, you should use the bundled files only in the production environment. You can specify which file to use in which environment by using &lt;strong&gt;Environment&lt;/strong&gt; Tag Helper. If you want to learn more about Tag Helpers then you can read my post &lt;a href="https://www.ezzylearning.net/tutorial/a-developer-guide-to-asp-net-core-tag-helpers" rel="noopener noreferrer"&gt;A Developer Guide to ASP.NET Core Tag Helpers&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The Environment Tag Helper only renders its contents when the application is running in specific environments. The following code snippet shows how to use environment tag helper to render non-bundled files in the Development environment and bundled files when the environment is not Development such as Production or Staging. You can add the following environment tag helper in &lt;strong&gt;_Layout.cshtml&lt;/strong&gt; file.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;environment include="Development"&amp;gt;
  &amp;lt;link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /&amp;gt;
  &amp;lt;link rel="stylesheet" href="~/css/site.css" /&amp;gt;
&amp;lt;/environment&amp;gt;

&amp;lt;environment exclude="Development"&amp;gt;
  &amp;lt;link rel="stylesheet" href="~/css/main.min.css" asp-append-version="true" /&amp;gt;
&amp;lt;/environment&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can use same environment tag helper to render our JavaScript files as follows:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;environment include="Development"&amp;gt;
    &amp;lt;script src="~/lib/jquery/dist/jquery.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/lib/bootstrap/dist/js/bootstrap.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/js/site.js" asp-append-version="true"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/environment&amp;gt;

&amp;lt;environment exclude="Development"&amp;gt;
    &amp;lt;link rel="stylesheet" href="~/js/main.min.js" asp-append-version="true" /&amp;gt;
&amp;lt;/environment&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you will build and run your project now, you will see the following CSS and JavaScript files will be included on your website. This is because you are currently in the Development environment.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" /&amp;gt;
&amp;lt;link rel="stylesheet" href="/css/site.css" /&amp;gt;
...
...
...
&amp;lt;script src="/lib/jquery/dist/jquery.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src="/lib/bootstrap/dist/js/bootstrap.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src="/js/site.js?v=4q1jwFhaPaZgr8"&amp;gt;&amp;lt;/script&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can change your environment from Development to Production using the project properties dialog as shown in the following screenshot.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh0210y1iv4xcivcu78c1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh0210y1iv4xcivcu78c1.png" alt="Change Environment from Development to Production in Visual Studio"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you will run your project again, you will see the following bundled and minified files are included on your web page.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;&amp;lt;link rel="stylesheet" href="/css/main.min.css?v=GEO9YOMPwE4" /&amp;gt;&lt;br&gt;
...&lt;br&gt;
...&lt;br&gt;
...&lt;br&gt;
&amp;lt;link rel="stylesheet" href="/js/main.min.js?v=AHmIHyQd" /&amp;gt;&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  &lt;strong&gt;Using Bundler &amp;amp; Minifier Visual Studio Extension&lt;/strong&gt;&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;If you are using Visual Studio, it is a good idea to automate the bundling and minification process using a Visual Studio extension &lt;a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BundlerMinifier" rel="noopener noreferrer"&gt;Bundler &amp;amp; Minifier&lt;/a&gt; developed by &lt;a href="https://github.com/madskristensen" rel="noopener noreferrer"&gt;Mads Kristensen&lt;/a&gt;. This extension allows us to select and bundle files without writing a single line of code. You can download and install this extension from &lt;a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BundlerMinifier" rel="noopener noreferrer"&gt;Visual Studio Marketplace&lt;/a&gt;. You may be asked to close Visual Studio and re-open it during the installation of the extension.  &lt;/p&gt;

&lt;p&gt;Please note that if you want to use this extension then you don’t need the BuildBundlerMinifier NuGet package anymore. You can uninstall the BuildBundlerMinifier package from your project.&lt;/p&gt;

&lt;p&gt;If you will right-click on the bundleconfig.json file, you will see some new “Bundler &amp;amp; Minifier” related options available to you. You can Delete Bundle Output Files, Update Bundles, etc.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foaooo2a911povb2bd8es.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foaooo2a911povb2bd8es.png" alt="Bundler &amp;amp; Minifier Visual Studio 2019 Extension Options"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Similarly, if you will select and right-click on a single bundled file such as &lt;strong&gt;main.min.css&lt;/strong&gt;, you should see the option to “&lt;strong&gt;Re-minify File&lt;/strong&gt;” or an option to remove the file from bundling.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fesgi1rtwxxb2evejem0h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fesgi1rtwxxb2evejem0h.png" alt="Reminify bundle file in Visual Studio using Bundle and Minifier Extension"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This extension will also make your bundleconfig.json file recognizable in Task Runner Explorer. This will allow us to run bundling from Task Runner Explorer manually or we can trigger bundling when certain Visual Studio events occur such as Before or After Build.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ysa3ns3btaj6m9pmdb3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ysa3ns3btaj6m9pmdb3.png" alt="Task Runner Explorer shows bundleconfig JSON file in Visual Studio 2019"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To execute the bundle from Task Runner Explorer, right-click on “&lt;strong&gt;Update all files&lt;/strong&gt;” option and click “&lt;strong&gt;Run&lt;/strong&gt;” option and you will see the bundled files are generated in your project Solution Explorer.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frqmje1xjzk5b3gxolujz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frqmje1xjzk5b3gxolujz.png" alt="Bundling and Minification using Task Runner Explorer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Summary&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In this tutorial, I have given you a basic overview of bundling and minification. I have also shown you some packages, tools, and extensions available for handling bundling and minification in our projects. If you need more than bundling and minification such as linting, image optimization, cache busting, CDN, and so on then you can use task runners such as Gulp, Grunt, or Webpack. I will show you how to Gulp for bundling and minification in my next post.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>aspnetcore</category>
      <category>bundling</category>
      <category>minification</category>
    </item>
    <item>
      <title>How to Consume Third-party Web APIs in ASP.NET Core</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Sat, 28 Aug 2021 09:41:27 +0000</pubDate>
      <link>https://dev.to/ezzylearning/how-to-consume-third-party-web-apis-in-asp-net-core-16d4</link>
      <guid>https://dev.to/ezzylearning/how-to-consume-third-party-web-apis-in-asp-net-core-16d4</guid>
      <description>&lt;p&gt;In modern web applications, it is very common to call third-party Web APIs to enhance the functionality of the application. There are thousands of free and commercial APIs available and if you know how to consume those APIs in your ASP.NET Core Applications, you can build very powerful business applications. In my previous post &lt;a href="https://www.ezzylearning.net/tutorial/a-developers-guide-for-creating-web-apis-with-asp-net-core-5" rel="noopener noreferrer"&gt;A Developer’s Guide for Creating Web APIs with ASP.NET Core 5&lt;/a&gt;, I covered ASP.NET Core Web APIs in detail. In this post, I will explain how you can consume third-party Web APIs in ASP.NET Core applications.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/ConsumeThirdPartyApisDemo" rel="noopener noreferrer"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Overview of Third Party API
&lt;/h2&gt;

&lt;p&gt;We will develop an application that will allow the user to input a country code and a year and then we will call a third party API to fetch the list of public holidays of that particular country in that particular year. The third-party API we will consume is called &lt;a href="https://date.nager.at/" rel="noopener noreferrer"&gt;Nager.Date&lt;/a&gt; which is a worldwide public holidays API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F27mkl8cnwfdg607051yu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F27mkl8cnwfdg607051yu.png" alt="Nager.Date World Wide Public Holidays API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is a very simple API and you can easily test this API in Postman by entering the following URL.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://date.nager.at/api/v2/PublicHolidays/2020/US" rel="noopener noreferrer"&gt;https://date.nager.at/api/v2/PublicHolidays/2020/US&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The response of this API is the list of public holidays in JSON format as shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxfxdwo1qo3d2vb9cqlh0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxfxdwo1qo3d2vb9cqlh0.png" alt="World Wide Public Holidays API in Postman"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding HttpClient Object
&lt;/h2&gt;

&lt;p&gt;The most common and well knows class that allows us to consume third-party APIs in ASP.NET Core application is &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0" rel="noopener noreferrer"&gt;HttpClient&lt;/a&gt; class. This class gives us the ability to send HTTP requests to third-party APIs and receive HTTP responses returned from those APIs. Every instance of HttpClient maintains its own connection pool that allows it to isolate its requests from requests executed by other instances of HttpClient. This class also acts as a base class for more specific HTTP clients. For example, you can create FacebookHttpClient or TwitterHttpClient as child classes of base HttpClient and can communicate with Facebook and Twitter APIs using these specific HTTP clients.&lt;/p&gt;

&lt;p&gt;It is recommended to create one instance of HttpClient and reuse it throughout the application lifetime. This is because instantiating a new instance of HttpClient for every request can easily exhaust the number of sockets available under heavy loads. This is mainly because when the HttpClient object is disposed of the underlying socket is not immediately released. You can read this wonderful blog post &lt;a href="https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/" rel="noopener noreferrer"&gt;You're using HttpClient wrong and it's destabilizing your software&lt;/a&gt; to get more information about the problem I just mentioned.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using HttpClient in ASP.NET Core
&lt;/h2&gt;

&lt;p&gt;As I mentioned above that we will create an application that will allow the user to view the list of public holidays in any country. Let’s create an ASP.NET Core MVC Web Application and create the following interface. This interface has just one method GetHolidays which has two parameters countryCode and year which we will receive from the user shortly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IHolidaysApiService
{
    Task&amp;lt;List&amp;lt;HolidayModel&amp;gt;&amp;gt; GetHolidays(string countryCode, int year);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The GetHolidays method above is returning a list of HolidayModel which is a model class that has the properties mapped with the response of &lt;a href="https://date.nager.at/" rel="noopener noreferrer"&gt;Nag&lt;/a&gt;&lt;a href="https://date.nager.at/" rel="noopener noreferrer"&gt;e&lt;/a&gt;&lt;a href="https://date.nager.at/" rel="noopener noreferrer"&gt;r.Date&lt;/a&gt; API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HolidayModel
{
    public string Name { get; set; }
    public string LocalName { get; set; }
    public DateTime? Date { get; set; }
    public string CountryCode { get; set; }
    public bool Global { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to implement a HolidaysApiService class that will implement the IHolidaysApiService declared above. Note how I have declared a private and static HttpClient variable in the class and how it is defined in the static constructor of the class. It is the recommended way of creating HttpClient instances as mentioned on Microsoft &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0" rel="noopener noreferrer"&gt;official docs&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HolidaysApiService : IHolidaysApiService
{
    private static readonly HttpClient client;

    static HolidaysApiService()
    {
        client = new HttpClient()
        {
            BaseAddress = new Uri("https://date.nager.at")
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we need to define GetHolidays method as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task&amp;lt;List&amp;lt;HolidayModel&amp;gt;&amp;gt; GetHolidays(string countryCode, int year)
{
    var url = string.Format("/api/v2/PublicHolidays/{0}/{1}", year, countryCode);
    var result = new List&amp;lt;HolidayModel&amp;gt;();
    var response = await client.GetAsync(url);
    if (response.IsSuccessStatusCode)
    {
        var stringResponse = await response.Content.ReadAsStringAsync();

        result = JsonSerializer.Deserialize&amp;lt;List&amp;lt;HolidayModel&amp;gt;&amp;gt;(stringResponse,
            new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
    }
    else
    {
        throw new HttpRequestException(response.ReasonPhrase);
    }

    return result;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A lot is happening in the above method so let me explain it all in detail:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first line is building the &lt;strong&gt;Url&lt;/strong&gt; of &lt;a href="https://date.nager.at/" rel="noopener noreferrer"&gt;Nager.Date&lt;/a&gt; API and using the &lt;strong&gt;year&lt;/strong&gt; and &lt;strong&gt;countryCode&lt;/strong&gt; parameters
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var url = string.Format("/api/v2/PublicHolidays/{0}/{1}", year, countryCode);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Next, we are making an API call using the &lt;strong&gt;GetAsync&lt;/strong&gt; method that sends a GET request to the specified Uri as an asynchronous operation. The method returns &lt;strong&gt;System.Net.Http.HttpResponseMessage&lt;/strong&gt; object that represents an HTTP response message including the status code and data.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var response = await client.GetAsync(url);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Next, we are calling &lt;strong&gt;ReadAsStringAsync&lt;/strong&gt; method that serializes the HTTP content to a string
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var stringResponse = await response.Content.ReadAsStringAsync();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Finally, we are using &lt;strong&gt;JsonSerializer&lt;/strong&gt; to Deserialize the JSON response string into a List of &lt;strong&gt;HolidayModel&lt;/strong&gt; objects.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = JsonSerializer.Deserialize&amp;lt;List&amp;lt;HolidayModel&amp;gt;&amp;gt;(stringResponse,
    new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s all we need to consume a third part Public Holidays API. To use our &lt;strong&gt;HolidaysApiService&lt;/strong&gt;, we need to first register our service in &lt;strong&gt;Startup.cs&lt;/strong&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddSingleton&amp;lt;IHolidaysApiService, HolidaysApiService&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we can inject our &lt;strong&gt;HolidaysApiService&lt;/strong&gt; in our &lt;strong&gt;HomeController&lt;/strong&gt; and call the &lt;strong&gt;GetHolidays&lt;/strong&gt; method by passing the countryCode and year parameter we will receive inside the Index action method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HomeController : Controller
{
    private readonly IHolidaysApiService _holidaysApiService;

    public HomeController(IHolidaysApiService holidaysApiService)
    {
        _holidaysApiService = holidaysApiService;
    } 

    public async Task&amp;lt;IActionResult&amp;gt; Index(string countryCode, int year)
    {
        List&amp;lt;HolidayModel&amp;gt; holidays = new List&amp;lt;HolidayModel&amp;gt;();
        holidays = await _holidaysApiService.GetHolidays(countryCode, year);

        return View(holidays);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, we need a Razor View to create a form where the user will input country code and year. The form will be submitted to the above Index action which will then call the &lt;strong&gt;GetHolidays&lt;/strong&gt; method. Here is the code of &lt;strong&gt;Index.cshtml&lt;/strong&gt; Razor view showing an HTML form and a table to display the public holidays.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@model List&amp;lt;HolidayModel&amp;gt;
@{
    ViewData["Title"] = "Home Page";
}
&amp;lt;div&amp;gt;
    &amp;lt;h3 class="display-4"&amp;gt;Public Holidays Finder&amp;lt;/h3&amp;gt;
    &amp;lt;center&amp;gt;
        &amp;lt;form asp-controller="Home" asp-action="Index"&amp;gt;
            &amp;lt;table&amp;gt;
                &amp;lt;tr&amp;gt;
                    &amp;lt;td&amp;gt;Country Code: &amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;&amp;lt;input type="text" id="txtCountryCode" name="CountryCode" /&amp;gt;&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;Year: &amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;&amp;lt;input type="text" id="txtYear" name="Year" /&amp;gt;&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;&amp;lt;input type="submit" value="Submit" /&amp;gt;&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/table&amp;gt;
            &amp;lt;hr /&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/center&amp;gt;
    @if (Model != null &amp;amp;&amp;amp; Model.Count &amp;gt; 0)
    {
        &amp;lt;table class="table table-bordered table-striped table-sm"&amp;gt;
            &amp;lt;thead&amp;gt;
            &amp;lt;tr&amp;gt;
                &amp;lt;th&amp;gt;Date&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;Name&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;Local Name&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;Country Code&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;Global&amp;lt;/th&amp;gt;
            &amp;lt;/tr&amp;gt;
            &amp;lt;/thead&amp;gt;
            &amp;lt;tbody&amp;gt;
            @foreach (var item in Model)
            {
                &amp;lt;tr&amp;gt;
                    &amp;lt;td&amp;gt;@item.Date.Value.ToShortDateString()&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;@Html.DisplayFor(modelItem =&amp;gt; item.Name)&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;@Html.DisplayFor(modelItem =&amp;gt; item.LocalName)&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;@Html.DisplayFor(modelItem =&amp;gt; item.CountryCode)&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;@Html.DisplayFor(modelItem =&amp;gt; item.Global)&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            }
            &amp;lt;/tbody&amp;gt;
        &amp;lt;/table&amp;gt;
    }

&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is now time to test our application and see if we will be able to consume the third Party API. Press F5 in Visual Studio and you will see a page similar to the following. You can input a country code e.g. US, DE, etc., and a year e.g. 2021, and click the “Submit” button and if everything goes well you will see our code calling a third-party API, fetching a list of Public Holidays from the API and displaying it on the page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa4qq8ikcwfssus6vsnen.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa4qq8ikcwfssus6vsnen.png" alt="Public Holidays Finder Application with ASP.NET Core and Third-Party API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Managing HttpClient objects with IHttpClientFactory&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To make &lt;code&gt;HttpClient&lt;/code&gt; instances manageable, and to avoid the socket exhaustion issue mentioned above, .NET Core 2.1 introduced the &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.ihttpclientfactory" rel="noopener noreferrer"&gt;IHttpClientFactory&lt;/a&gt; interface which can be used to configure and create HttpClient instances in an app through Dependency Injection (DI). To make use of &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.ihttpclientfactory?view=dotnet-plat-ext-5.0" rel="noopener noreferrer"&gt;IHttpClientFactory&lt;/a&gt;, we can register it in Startup.cs file by calling &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientfactoryservicecollectionextensions.addhttpclient?view=dotnet-plat-ext-5.0#Microsoft_Extensions_DependencyInjection_HttpClientFactoryServiceCollectionExtensions_AddHttpClient_Microsoft_Extensions_DependencyInjection_IServiceCollection_" rel="noopener noreferrer"&gt;AddHttpClient(IServiceCollection)&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddSingleton&amp;lt;IHolidaysApiService, HolidaysApiService&amp;gt;();

    services.AddHttpClient("PublicHolidaysApi", c =&amp;gt; c.BaseAddress = new Uri("https://date.nager.at"));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is possible to register multiple HTTP clients with different names using the &lt;strong&gt;AddHttpClient&lt;/strong&gt; method. The first parameter of the AddHttpClient method is the &lt;strong&gt;name&lt;/strong&gt; of the client and the second parameter is the Lamba expression that will configure the &lt;strong&gt;HttpClient&lt;/strong&gt;. In the above example, I am setting the &lt;strong&gt;BaseAddress&lt;/strong&gt; property with the Url of the third-party API I want to call using this particular HTTP client.&lt;/p&gt;

&lt;p&gt;Once the HTTP Client is registered, we can inject &lt;strong&gt;IHttpClientFactory&lt;/strong&gt; in our controllers and services and call its &lt;strong&gt;CreateClient&lt;/strong&gt; method to create a specific HTTP Client object we want to use in our code. The CreateClient method needs the name of the HTTP Client you want to create as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HolidaysApiService : IHolidaysApiService
{
    private readonly HttpClient client;

    public HolidaysApiService(IHttpClientFactory clientFactory)
    {
        client = clientFactory.CreateClient("PublicHolidaysApi");
    }

    public async Task&amp;lt;List&amp;lt;HolidayModel&amp;gt;&amp;gt; GetHolidays(string countryCode, int year)
    {
        var url = string.Format("/api/v2/PublicHolidays/{0}/{1}", year, countryCode);
        var result = new List&amp;lt;HolidayModel&amp;gt;();
        var response = await client.GetAsync(url);
        if (response.IsSuccessStatusCode)
        {
            var stringResponse = await response.Content.ReadAsStringAsync();

            result = JsonSerializer.Deserialize&amp;lt;List&amp;lt;HolidayModel&amp;gt;&amp;gt;(stringResponse,
                new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
        }
        else
        {
            throw new HttpRequestException(response.ReasonPhrase);
        }

        return result;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;In this article, I have given you an overview of HttpClient and also gave you examples of creating HttpClient objects directly or using IHttpClientFactory. I also showed you an example of invoking a third part Web API using HttpClient. I hope you are now familiar with the HttpClient object and its usage and will start using it in your projects with confidence.&lt;/p&gt;

</description>
      <category>aspnetcore</category>
      <category>webapi</category>
      <category>dotnet</category>
      <category>programming</category>
    </item>
    <item>
      <title>7 Best News Websites Developers Should Follow in 2021
</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Sat, 28 Aug 2021 08:51:27 +0000</pubDate>
      <link>https://dev.to/ezzylearning/7-best-news-websites-developers-should-follow-in-2021-ck2</link>
      <guid>https://dev.to/ezzylearning/7-best-news-websites-developers-should-follow-in-2021-ck2</guid>
      <description>&lt;p&gt;The tech industry is changing very rapidly and it is important for programmers and developers to stay up to date on the latest technologies, frameworks and advancements. It is important to know where the industry is going, what is trending and what is become obsolete, what will be popular in future and what are the latest tools and trends others are adopting to become more productive. While this all seem like a daunting task especially if you don’t know where to start and where to look for this all this interesting information. It is also important to know that we have access to best and most reliable information sources. I have decided to share a list of some of the best news websites for programmers and developers. I regularly visit these websites and believe me I always learn something new and interesting every time I visit these websites.&lt;/p&gt;

&lt;h2&gt;
  
  
  DEV
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://dev.to/"&gt;https://dev.to/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iMhz-7Rk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6g4zwpz09pfbenvdb2y.png" alt="DEV"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;DEV is a community of amazing software developers where coders share, stay up-to-date and grow their careers. The software industry relies on collaboration and sharing of information and DEV is the place where developers get together and contribute for the overall growth of the industry. The website is very well organized and you can browse news feed by time period e.g. Week, Month etc. or you can also find news by tags e.g. #javascript, #python etc. There are also separate sections for Podcasts and Videos which are always favorite type of content for developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lobsters
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://lobste.rs/"&gt;https://lobste.rs/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Lobsters is a computing-focused community centered around link aggregation and discussion. They have a tagging system to categorize and filter stories by tags e.g. Programming, JavaScript etc. The stories and comments can be ranked by users which is very useful to find the top ranked stories in different areas. They also have a concept of user tree which shows who is invited by whom. Other useful features are mailing list mode, integrated search engine and story merging and flag explanations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hashnode
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://hashnode.com/"&gt;https://hashnode.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://hashnode.com/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QETNvWBB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bz7pocyutfjceglsxrib.png" alt="Hashnode"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Hashnode is a global dev community with the mission of connecting world’s developers and help them share their knowledge. Many developers around the world have their blogs on Hashnode platform and you can easily find fresh content on any topic you are interested in. You can also follow the tag you are interested in and filter the blogs and posts by those tags. You can also explore the blogs with most followers which will give you access to top notch developer content.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hacker Noon
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.hackernoon.com/"&gt;https://www.hackernoon.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.hackernoon.com/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yE22TTpW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u4q11dmcxy8camwoqzy8.png" alt="hackernoon"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Hacker Noon is an American technology publishing website. It focuses on reporting the latest news related to software development, startups, artificial intelligence, and cryptocurrencies. It is considered as a heaven for programmers because of wide range of tutorials, videos and latest programming news posted by 15K+ active contributing writers and read by 3M+ monthly readers.&lt;/p&gt;

&lt;h2&gt;
  
  
  XDA Developers
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.xda-developers.com/"&gt;https://www.xda-developers.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.xda-developers.com/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YRUL_o78--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2zxleolvhbbcfuynldgq.png" alt="xda-developers"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;XDA Developers was founded by developers, for developers. It is a mobile software development community launched on 20 December 2002. Although discussion primarily revolves around Android, members also talk about many other operating systems and mobile development topics. XDA Developers also hosts the XDA Portal, a source for Android and mobile phone development news, as well as XDA Labs, an Android app and repository that acts as a third-party application provider.&lt;/p&gt;

&lt;h2&gt;
  
  
  Product Hunt
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.producthunt.com/"&gt;https://www.producthunt.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.producthunt.com/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zV-4F7aR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cognxzutnq8386cl3goc.png" alt="Product Hunt"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Product Hunt is an American website to share and discover new products founded by Ryan Hoover in November 2013. Product Hunt surfaces the best new products, every day. It's a place for product-loving enthusiasts to share and geek out about the latest mobile apps, websites, hardware projects, and tech creations.&lt;/p&gt;

&lt;h2&gt;
  
  
  TechCrunch
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://techcrunch.com/"&gt;https://techcrunch.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://techcrunch.com/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--x_IB_b2---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ul0xl0ap8lgjomry7vka.png" alt="TechCrunch"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;TechCrunch is an American online technology news and analysis website focusing on high tech and startup companies. TechCrunch is also best known for its Disrupt conferences, an annual technology event hosted in several cities across United States, Europe, and China. Other than the news about tech startups, they have a videos section that lists the videos about latest apps and gadgets. If you love podcasts then you will enjoy their podcasts Equity, MixTape and Original Content.&lt;/p&gt;

</description>
      <category>developers</category>
      <category>news</category>
      <category>websites</category>
      <category>programming</category>
    </item>
    <item>
      <title>A Developer’s Guide for Creating Web APIs with ASP.NET Core 5</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Wed, 25 Aug 2021 18:47:14 +0000</pubDate>
      <link>https://dev.to/ezzylearning/a-developer-s-guide-for-creating-web-apis-with-asp-net-core-5-330a</link>
      <guid>https://dev.to/ezzylearning/a-developer-s-guide-for-creating-web-apis-with-asp-net-core-5-330a</guid>
      <description>&lt;p&gt;The Web APIs (aka RESTful Services) are the type of applications that don’t return views in response, instead, they usually consume and return data in a machine-readable format such as XML or JSON. This concept is not new and the main goal of building Web APIs is to serve data to multiple client apps in a centralized way. As the number of the connected apps increase, the usage of the Web APIs can also grow significantly so it is very important to keep in mind the maintainability and scalability in mind. ASP.NET Core provides some powerful features to write Web APIs that comply with the REST standards. This tutorial will serve as a useful guide on how to build and consume Web APIs using the latest version of ASP.NET Core 5.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/AspNetCore5WebApisDemo" rel="noopener noreferrer"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Introducing ASP.NET Core Web API&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;An ASP.NET Core Web API consists of one or more controller classes that derive from &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase" rel="noopener noreferrer"&gt;&lt;strong&gt;ControllerBase&lt;/strong&gt;&lt;/a&gt;. The ControllerBase class provides many properties and methods that are useful for handling HTTP requests You can also derive your class from a &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controller" rel="noopener noreferrer"&gt;&lt;strong&gt;Controller&lt;/strong&gt;&lt;/a&gt; class which derives from &lt;strong&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase" rel="noopener noreferrer"&gt;ControllerBase&lt;/a&gt;&lt;/strong&gt; but that is only recommended if you want to create the same controller for Web APIs and Views.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fihsgi2uv5wgavo9nq6ie.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fihsgi2uv5wgavo9nq6ie.png" alt="ASP.NET Core Web APIs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here are some common methods that ControllerBase provides.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Method&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Notes&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;BadRequest&lt;/td&gt;
&lt;td&gt;Returns 400 status code.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NotFound&lt;/td&gt;
&lt;td&gt;Returns 404 status code.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;PhysicalFile&lt;/td&gt;
&lt;td&gt;Returns a file.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;TryUpdateModelAsync&lt;/td&gt;
&lt;td&gt;Invokes model binding.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;TryValidateModel&lt;/td&gt;
&lt;td&gt;Invokes model validation.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc" rel="noopener noreferrer"&gt;Microsoft.AspNetCore.Mvc&lt;/a&gt; namespace provides some attributes that can be used to configure the behavior of web API controllers and action methods. The following example uses attributes to specify the supported HTTP action verb and any known HTTP status codes that could be returned:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[HttpPost] 
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult&amp;lt;Book&amp;gt; Create(Book book)
{
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here are some common attributes available.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Attribute&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Notes&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;[Route]&lt;/td&gt;
&lt;td&gt;Specifies URL pattern for a controller or action.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;[Bind]&lt;/td&gt;
&lt;td&gt;Specifies prefix and properties to include for model binding.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;[HttpGet]&lt;/td&gt;
&lt;td&gt;Identifies an action that supports the HTTP GET action verb.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;[Consumes]&lt;/td&gt;
&lt;td&gt;Specifies data types that an action accepts.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;[Produces]&lt;/td&gt;
&lt;td&gt;Specifies data types that an action returns.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;One of the important attributes is &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.apicontrollerattribute" rel="noopener noreferrer"&gt;[ApiController]&lt;/a&gt; that can be applied to a controller class to enable some special features such as Attribute Routing, Automatic HTTP 400 response, etc. These additional features and behavior improve the developer experience for building APIs.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Creating ASP.NET Core 5 Web API Project&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If you are using Visual Studio 2019, then from the &lt;strong&gt;File&lt;/strong&gt; menu, select &lt;strong&gt;New&lt;/strong&gt; &amp;gt; &lt;strong&gt;Project&lt;/strong&gt;. Select the &lt;strong&gt;ASP.NET Core Web Application&lt;/strong&gt; template and click &lt;strong&gt;Next&lt;/strong&gt;. Give your project a name and click &lt;strong&gt;Create&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In the &lt;strong&gt;Create a new ASP.NET Core Web Application&lt;/strong&gt; dialog, confirm that &lt;strong&gt;.NET Core&lt;/strong&gt; and &lt;strong&gt;ASP.NET Core 5.0&lt;/strong&gt; are selected. Select the &lt;strong&gt;ASP.NET Core Web API&lt;/strong&gt; template and click &lt;strong&gt;Create&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhzsn0573d37156gwhctm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhzsn0573d37156gwhctm.png" alt="Creating ASP.NET Core 5 Web API Project"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The project template will create a default weather forecast API for you. Press &lt;strong&gt;Ctrl+F5&lt;/strong&gt; to run without the debugger. You will see the following URL in the browser address bar&lt;/p&gt;

&lt;p&gt;&lt;a href="https://localhost:/WeatherForecast" rel="noopener noreferrer"&gt;https://localhost:/WeatherForecast&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and that JSON similar to the following will return from the API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
   {
      "date":"2020-12-26T16:57:09.1646732+05:00",
      "temperatureC":20,
      "temperatureF":67,
      "summary":"Cool"
   },
   {
      "date":"2020-12-27T16:57:09.1669352+05:00",
      "temperatureC":51,
      "temperatureF":123,
      "summary":"Hot"
   },
   {
      "date":"2020-12-28T16:57:09.1669397+05:00",
      "temperatureC":29,
      "temperatureF":84,
      "summary":"Hot"
   }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The default Web API project template has created the following &lt;strong&gt;WeatherForecast&lt;/strong&gt; model class that has some basic weather related properties.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF =&amp;gt; 32 + (int)(TemperatureC / 0.5556);
    public string Summary { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The project template will also create a default &lt;strong&gt;WeatherForecastController&lt;/strong&gt; class that is derived from the &lt;strong&gt;ControllerBase&lt;/strong&gt; class. The class is also decorated with &lt;strong&gt;[Route]&lt;/strong&gt; and &lt;strong&gt;[ApiController]&lt;/strong&gt; attributes mentioned above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another important thing to notice is that the &lt;strong&gt;ConfigureServices&lt;/strong&gt; method of Startup.cs class is calling &lt;strong&gt;AddControllers&lt;/strong&gt; method and not &lt;strong&gt;AddMvc&lt;/strong&gt; method. This is because if you are not using MVC related features in your Web APIs and you want to keep your Web APIs lightweight with minimum required features then you don’t need to register additional MVC related features.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another important piece of code in Startup.cs is where a feature called endpoint routing is configured using the following statements. This allows us to define endpoint routes using the &lt;strong&gt;[Route]&lt;/strong&gt; attribute on top of Web API controllers and actions. We have already seen an example above where &lt;strong&gt;[Route("[controller]")]&lt;/strong&gt; attribute is set on &lt;strong&gt;WeatherForecastController&lt;/strong&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.UseEndpoints(endpoints =&amp;gt;
{
   endpoints.MapControllers();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final noticeable thing in the project is the settings configured in &lt;strong&gt;Properties\launchSettings.json&lt;/strong&gt; file which specifies different launch profiles and &lt;strong&gt;launchUrl&lt;/strong&gt; etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"IIS Express": {
    "commandName": "IISExpress",
    "launchBrowser": true,
    "launchUrl": "weatherforecast",
    "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Implement CRUD Operations using ASP.NET Core Web API&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Now you have the basic knowledge of Web APIs and you have also seen the default Web API created by you using the Visual Studio Web API project template. It is now time to implement our Web APIs and learn Web APIs in more detail. For this tutorial, I have decided to write a fictional web API for a library management system. We will create a RESTful service that allows client applications to manage the library books catalog. The API needs to expose endpoints to create, read, edit, and delete books.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;API&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Description&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Request body&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Response body&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;strong&gt;GET&lt;/strong&gt; /api/books&lt;/td&gt;
&lt;td&gt;Get all books&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;td&gt;Array of books&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;strong&gt;GET&lt;/strong&gt; /api/books/{id}&lt;/td&gt;
&lt;td&gt;Get a book by Id&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;td&gt;Book&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;strong&gt;POST&lt;/strong&gt; /api/books&lt;/td&gt;
&lt;td&gt;Add a new book&lt;/td&gt;
&lt;td&gt;Book&lt;/td&gt;
&lt;td&gt;Book&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;strong&gt;PUT&lt;/strong&gt; /api/books/{id}&lt;/td&gt;
&lt;td&gt;Update an existing book  &lt;/td&gt;
&lt;td&gt;Book&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;strong&gt;DELETE&lt;/strong&gt; /api/books/{id}    &lt;/td&gt;
&lt;td&gt;Delete a book    &lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The first thing we need is the Book model class. A model class is a class that represents the data associated with an entity e.g. Book. Create a Models folder in the project and add the following class in the Models folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int YearPublished { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Id property functions as the unique key in a relational database. A book model in a real library system can have dozens of other properties but to keep the example simple, I won’t add any other functionality in the Book class.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Creating Database Context&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To handle database operations, we need the Entity Framework data context class. This class represents a session with the database and can be used to query and save instances of your entities e.g. Book. This class is created by deriving from &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.DbContext&lt;/a&gt; class. Creating a real SQL Server database and managing our books inside the real database is also out of the scope for this tutorial so I have decided to use &lt;a href="https://docs.microsoft.com/en-us/ef/core/providers/in-memory/?tabs=dotnet-core-cli" rel="noopener noreferrer"&gt;Microsoft.EntityFrameworkCore.InMemory&lt;/a&gt; data provider. This database provider allows Entity Framework Core to be used with an in-memory database. The in-memory database is useful when you want to test some basic database operations without the need of creating a real database. You can download and install both of these packages using the NuGet package manager.&lt;/p&gt;

&lt;p&gt;If you don’t know how to use NuGet package manager to install third-party libraries and packages then I will recommend you to read my post &lt;a href="https://www.ezzylearning.net/tutorial/working-with-packages-and-libraries-in-asp-net-core" rel="noopener noreferrer"&gt;Working with Packages and Libraries in ASP.NET Core&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you have the above packages installed, create the following &lt;strong&gt;LibraryContext&lt;/strong&gt; data context class in your project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class LibraryContext : DbContext
{
    public LibraryContext(DbContextOptions&amp;lt;LibraryContext&amp;gt; options)
        : base(options)
    {
    }

    public DbSet&amp;lt;Book&amp;gt; Books { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to register our database context object with the dependency injection container. This will allow us to inject and use our library context in controllers and services. Notice we also specified below that we want to use an in-memory database provider with the database name “&lt;strong&gt;LibraryDb&lt;/strong&gt;”. This in-memory database will be used to store our books entities later in this tutorial.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext&amp;lt;LibraryContext&amp;gt;(opt =&amp;gt; opt.UseInMemoryDatabase("LibraryDb"));

    services.AddControllers();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to learn more about dependency injection then you can read my post &lt;a href="https://www.ezzylearning.net/tutorial/a-step-by-step-guide-to-asp-net-core-dependency-injection" rel="noopener noreferrer"&gt;A Step by Step Guide to ASP.NET Core Dependency Injection&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Scaffolding Web API Controller in Visual Studio&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;You can either create Web API controllers manually and implement all those CRUD operations related actions manually or you can take advantage of Visual Studio built-in scaffolding feature and save some time. To create our &lt;strong&gt;BookController&lt;/strong&gt;, right click on the “&lt;strong&gt;Controllers&lt;/strong&gt;” folder and choose the &lt;strong&gt;Add&lt;/strong&gt; &amp;gt; &lt;strong&gt;Controller&lt;/strong&gt;… option. You will see the following dialog in which you need to select “&lt;strong&gt;API&lt;/strong&gt;” from the left-hand side pane. Next select the “&lt;strong&gt;API Controller with actions, using Entity Framework&lt;/strong&gt;” option and click the “Add” button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fevhd7sjrfcsljnybo5h3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fevhd7sjrfcsljnybo5h3.png" alt="Add New Scaffold Item Dialog in Visual Studio"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The following dialog will appear where you can provide the name of your controller along with the Model and Data context classes. Click the “&lt;strong&gt;Add&lt;/strong&gt;” button when you have provided all details as shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkwg5oldl24iole8t9gee.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkwg5oldl24iole8t9gee.png" alt="Add API Controller with Actions using Entity Framework"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A standard API controller will be generated for you along with all the actions. Notice that the class is marked with the &lt;strong&gt;[ApiController]&lt;/strong&gt; attribute mentioned above and a &lt;strong&gt;LibraryContext&lt;/strong&gt; object is also injected in the constructor of the controller.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
    private readonly LibraryContext _context;

    public BooksController(LibraryContext context)
    {
        _context = context;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To save us some typing, the following actions are also generated automatically for you.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1er8egvmlqqjw0dyqos8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1er8egvmlqqjw0dyqos8.png" alt="ASP.NET Core Web API Action methods for CRUD operations"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Understanding Web API Action Methods&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The first action method we will explore is the &lt;strong&gt;PostBook&lt;/strong&gt; action method. This method will be used to add new books to our in-memory database. The &lt;strong&gt;[HttpPost]&lt;/strong&gt; attribute indicates that this action will be called using the HTTP POST method. The method has a parameter e.g. Book that will be passed to this action from the body of the HTTP request.&lt;/p&gt;

&lt;p&gt;The first statement will add the book object in the Books collection available in our data context and the second statement will persist our changes to the database. The last statement is calling the &lt;strong&gt;CreatedAtAction&lt;/strong&gt; method that will automatically return &lt;strong&gt;HTTP 201 status code&lt;/strong&gt; and will also add a &lt;strong&gt;Location&lt;/strong&gt; header to the response. This Location header specifies the URI of the newly created book.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// POST: api/Books
[HttpPost]
public async Task&amp;lt;ActionResult&amp;lt;Book&amp;gt;&amp;gt; PostBook(Book book)
{
    _context.Books.Add(book);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetBook", new { id = book.Id }, book);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can use tools like &lt;a href="https://www.getpostman.com/downloads/" rel="noopener noreferrer"&gt;Postman&lt;/a&gt; or &lt;a href="https://insomnia.rest/" rel="noopener noreferrer"&gt;Insomnia&lt;/a&gt; to test our APIs quickly without implementing a client application. You can download and install Postman from their &lt;a href="https://www.getpostman.com/downloads/" rel="noopener noreferrer"&gt;website&lt;/a&gt;. Once it's installed, create a new &lt;strong&gt;HTTP POST&lt;/strong&gt; request and set the &lt;strong&gt;URI&lt;/strong&gt; to our API URL. In the &lt;strong&gt;Body&lt;/strong&gt; tab, select the &lt;strong&gt;raw&lt;/strong&gt; radio button and choose type as &lt;strong&gt;JSON&lt;/strong&gt;. Finally, add the following JSON in the request body and click the &lt;strong&gt;Send&lt;/strong&gt; button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "title":"ASP.NET Web APIs Developer Guide",
  "yearPublished":2020
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Postman will call our &lt;strong&gt;PostBook&lt;/strong&gt; API mentioned above which will create a new book and finally will send &lt;strong&gt;201 Created&lt;/strong&gt; status code along with the newly created book as shown in the screenshot below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flrwfzdnomckau78269lo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flrwfzdnomckau78269lo.png" alt="New Entity Created using Post API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you will click the &lt;strong&gt;Headers&lt;/strong&gt; tab in Postman, you will notice the &lt;strong&gt;Location&lt;/strong&gt; header is showing the &lt;strong&gt;URI&lt;/strong&gt; to access the newly created book.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9an2b8zdpy9eflfeuvwd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9an2b8zdpy9eflfeuvwd.png" alt="Location Header in New API Response"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can copy-paste this URL in the browser address bar to view the newly created book.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9xahv3g1bx9izftfktho.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9xahv3g1bx9izftfktho.png" alt="Get Single Entity using ASP.NET Core Web API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The above URL is calling the following &lt;strong&gt;GetBook&lt;/strong&gt; action that simply searches the book in our in-memory database and return the book.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// GET: api/Books/5
[HttpGet("{id}")]
public async Task&amp;lt;ActionResult&amp;lt;Book&amp;gt;&amp;gt; GetBook(int id)
{
    var book = await _context.Books.FindAsync(id);

    if (book == null)
    {
        return NotFound();
    }

    return book;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this time, you can also test &lt;strong&gt;GetBooks&lt;/strong&gt; action in the browser that will return an array of all the books object available in our in-memory database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// GET: api/Books
[HttpGet]
public async Task&amp;lt;ActionResult&amp;lt;IEnumerable&amp;lt;Book&amp;gt;&amp;gt;&amp;gt; GetBooks()
{
    return await _context.Books.ToListAsync();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8de4dqgxhvk7jp01orya.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8de4dqgxhvk7jp01orya.png" alt="Get all Entities from ASP.NET Core Web API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The next method is the &lt;strong&gt;PutBook&lt;/strong&gt; method which can be used to update book entities. It uses the &lt;strong&gt;HTTP PUT&lt;/strong&gt; method and the id of the entity we want to update will be provided as a parameter in the &lt;strong&gt;URI&lt;/strong&gt;. The second parameter is the book entity that contains the updated data. The method will return &lt;strong&gt;400 Bad Request&lt;/strong&gt; if the specified id is not the same as the id property of the book entity we passed as the parameter. The response of the method will be &lt;strong&gt;204 No Content&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// PUT: api/Books/5
[HttpPut("{id}")]
public async Task&amp;lt;IActionResult&amp;gt; PutBook(int id, Book book)
{
    if (id != book.Id)
    {
        return BadRequest();
    }

    _context.Entry(book).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!BookExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return NoContent();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are using the in-memory database in this tutorial, so each time the application will start the new database will be initialized. We need to make sure that there is a book entity available in the database before we test the above &lt;strong&gt;PutBook&lt;/strong&gt; action method. The following screen shows the &lt;strong&gt;PUT&lt;/strong&gt; request we made with an updated entity &lt;strong&gt;JSON&lt;/strong&gt; in the body of the request.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffquitp448abnad9q42pz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffquitp448abnad9q42pz.png" alt="Update Entity using ASP.NET Core Web API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, we have the &lt;strong&gt;DeleteBook&lt;/strong&gt; action method that accepts requests with the &lt;strong&gt;HTTP DELETE&lt;/strong&gt; method and simply deletes the entity from the in-memory database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// DELETE: api/Books/5
[HttpDelete("{id}")]
public async Task&amp;lt;IActionResult&amp;gt; DeleteBook(int id)
{
    var book = await _context.Books.FindAsync(id);
    if (book == null)
    {
        return NotFound();
    }

    _context.Books.Remove(book);
    await _context.SaveChangesAsync();

    return NoContent();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following screenshot shows how to test the &lt;strong&gt;DeleteBook&lt;/strong&gt; action method in Postman.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqt2x69js2116rngwcnoo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqt2x69js2116rngwcnoo.png" alt="Delete Entity using ASP.NET Web API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;ASP.NET Core is a great framework to use when you are planning to build clean, scalable, and maintainable Web APIs. It has lots of useful APIs and features related to Web APIs and we can write a whole book on just Web APIs. This tutorial is a basic guide for developers who want to get started with ASP.NET Core Web APIs. I hope you enjoyed this tutorial and I will appreciate it if you can leave your feedback below to let me know how can I improve my tutorials further.&lt;/p&gt;

</description>
      <category>aspnetcore</category>
      <category>webapi</category>
      <category>developer</category>
      <category>guide</category>
    </item>
    <item>
      <title>Working with Packages and Libraries in ASP.NET Core</title>
      <dc:creator>EzzyLearning.net</dc:creator>
      <pubDate>Wed, 25 Aug 2021 18:46:48 +0000</pubDate>
      <link>https://dev.to/ezzylearning/working-with-packages-and-libraries-in-asp-net-core-4h0k</link>
      <guid>https://dev.to/ezzylearning/working-with-packages-and-libraries-in-asp-net-core-4h0k</guid>
      <description>&lt;p&gt;If you want to develop a modern web application, you will realize very quickly that you can’t write everything on your own. You will rely on some third party client and server side libraries and components to increase your development speed. There are many online code repositories and sources available to developers these days and downloading and keeping track of all third-party packages can be a painful task. Luckily developers now have many different tools and extensions available to them which can make this task a lot easier. In this tutorial, I will demonstrate how we can use tools like Node Package Manager (npm), Library Manager (LibMan), and Nuget to download and manage server and client-side libraries in ASP.NET Core projects.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezzylearning/PackagesLibrariesDemo"&gt;Download Source Code&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction to Node Package Manager (npm)
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/"&gt;npm&lt;/a&gt; is one of the world’s largest repository of client-side libraries and packages from where developers can download and install different open source libraries published and shared by other developers. Npm is a subsidiary of &lt;a href="https://github.com/"&gt;Github&lt;/a&gt; and is considered a default package manager for JavaScript runtime environment &lt;a href="https://nodejs.org/en/"&gt;Node.js&lt;/a&gt;. They also provide a command line tool (CLI) to developers for publishing and downloading third party libraries. In the past, the npm was used to be the package manager for just Node.js but now it is used by developers of other platforms and technologies as well.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Using npm from Command Line (CLI)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To use npm tool you need to make sure that you have downloaded and installed the Node.js on your machine. If you are using Windows, you can download the windows installer from &lt;a href="https://nodejs.org/en/"&gt;Node.js&lt;/a&gt;. website. Once you have the npm command line tool (CLI) available on your machine, you can go to your project folder and can use different npm commands to download and install packages.&lt;/p&gt;

&lt;p&gt;As a general rule, all projects using Node.js need to create a file called &lt;strong&gt;package.json&lt;/strong&gt; that contains the project information e.g. name, author, version as well as the information about the third party libraries you are downloading and managing in your project. You can either create this file yourself using a text editor or you can use one of the npm commands (init) to generate this file automatically. Npm init command is a step by step tool to generate your package.json file. You can initialize the project using npm init command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the command prompt in your project root folder and type the above command and press Enter.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YRqoRfqd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cttzkc211f6dxr9owu1h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YRqoRfqd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cttzkc211f6dxr9owu1h.png" alt="Using npm from command line"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;You will be asked to provide your project name, version, description, author, etc. If you don’t want to provide this information at this point, you can simply press Enter multiple times until you reach the last step where the tool will show you the sample package.json file and will ask you to confirm if the file looks ok to you. You can press enter one more time and a package.json file will be generated for you.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hyEvPZes--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sw4u8y2oaaqez1exq2qo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hyEvPZes--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sw4u8y2oaaqez1exq2qo.png" alt="npm init command"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, you can use the following command to download and install packages from npm online directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install &amp;lt;module&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above command, the &lt;strong&gt;module&lt;/strong&gt; is the name of the module you want to download. For example, if you want to install Express (which is a well known Node.js web framework), you can run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command will install the express module into &lt;strong&gt;/node_modules&lt;/strong&gt; in the current directory. Please note that whenever you will install a module from npm, it will be installed into the node_modules folder.&lt;/p&gt;

&lt;p&gt;If you will open package.json file now, you will see that metadata information about the express package is also recorded in the package.json file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "packageslibrariesdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \\"Error: no test specified\\" &amp;amp;&amp;amp; exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To see the full list of npm command you can visit npm docs &lt;a href="https://docs.npmjs.com/"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using npm from Visual Studio
&lt;/h2&gt;

&lt;p&gt;If you are not a fan of using command line interface (CLI) then you can use npm directly within Visual Studio. To use npm in Visual Studio you need to create npm configuration file using a built-in Visual Studio template. &lt;strong&gt;Right click&lt;/strong&gt; on your project in Visual Studio solution explorer and add a new file by choosing &lt;strong&gt;npm configuration file&lt;/strong&gt; template shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OwMt2u8w--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hxqs6z4eviig8dlo9nco.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OwMt2u8w--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hxqs6z4eviig8dlo9nco.png" alt="Add NPM Package JSON File in Visual Studio"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Visual Studio will automatically create a package.json file for you. Now you can specify which third party client side library you want to download and use in your project. You will also get some help from the built in IntelliSense which is very useful if you want to specify a specific version of the library.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2-hTdoPz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8a4dly1mzsdhi6bc3if.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2-hTdoPz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8a4dly1mzsdhi6bc3if.png" alt="Add client side libraries using NPM configuration file"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I am installing bootstrap 4.5.3 and as soon as you will save the file, you will see that the bootstrap package is downloaded in the node_modules folder and a dependency is also added under Dependencies node.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; If you are not seeing the node_modules folder then make sure “&lt;strong&gt;Show All Files&lt;/strong&gt;” option is on in Visual Studio Solution Explorer.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3iFp8XqX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oa05su57paru3wimnngj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3iFp8XqX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oa05su57paru3wimnngj.png" alt="npm dependencies and node modules folder in visual studio"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To uninstall the library, you just need to remove the &lt;strong&gt;“bootstrap”:”4.5.3”&lt;/strong&gt; line from your package.json file and as soon as you will save the file, bootstrap will be removed from your project.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Library Manager (LibMan)
&lt;/h2&gt;

&lt;p&gt;If you don’t want to use npm in your project, then Microsoft has another tool for you called &lt;a href="https://docs.microsoft.com/en-us/aspnet/core/client-side/libman/libman-vs"&gt;Library manager (LibMan)&lt;/a&gt;. LibMan is a lightweight tool for downloading libraries and packages from the files system or content delivery networks (CDN). Currently the tool support CDNs such as &lt;a href="https://cdnjs.com/"&gt;CDNJS&lt;/a&gt;, &lt;a href="https://www.jsdelivr.com/"&gt;jsDelivr&lt;/a&gt;, &lt;a href="https://unpkg.com/#/"&gt;unpkg&lt;/a&gt;. Just like npm, this tool can also be used from the command line or from within Visual Studio.&lt;/p&gt;

&lt;p&gt;To download LibMan tool CLI, you can type the following command in Windows PowerShell.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet tool install –g Microsoft.Web.LibraryManager.Cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--F5gl280B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc6fc8pvb85c9zuprwiw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--F5gl280B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc6fc8pvb85c9zuprwiw.png" alt="Installing LibMan CLI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Using LibMan from Command Line (CLI)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Once the tool is installed you can use ‘&lt;strong&gt;install&lt;/strong&gt;’ option to download packages. You can either specify the package name and the tool will download all files within that package or you can specify the files you need. For example, you can download only bootstrap.css file available in the bootstrap 4.5.3 package as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;libman install bootstrap@4.5.3 --files dist/css/bootstrap.css
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--p3D-IlQV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7pt6xm0lm36xehodx9v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--p3D-IlQV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7pt6xm0lm36xehodx9v.png" alt="download client libraries using LibMan CLI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To see the full list of available command you can visit LibMan docs &lt;a href="https://docs.microsoft.com/en-us/aspnet/core/client-side/libman/libman-cli?view=aspnetcore-5.0"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Using LibMan from Visual Studio&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;I am sure, some of you don’t like CLIs so you can use the LibMan tool inside Visual Studio as well. &lt;strong&gt;Right click&lt;/strong&gt; on your project in &lt;strong&gt;Solution Explorer&lt;/strong&gt; and choose &lt;strong&gt;Add &amp;gt; Client Side Library…&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YWyJ7uhm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m51yio14gdq8g5tvw42c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YWyJ7uhm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m51yio14gdq8g5tvw42c.png" alt="Add Client Side Libraries using LibMan Tool"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once the tool dialog is open, you can choose which Provide you want to use from the available CDNs. You can then search client side libraries and frameworks available in the selected provider online directory. For example, if you will start typing bootstrap, you will see that the tool is searching and populating the list of all libraries with your matching keyword.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--y-cjqQqv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9ij4fjn8kkhf0c1bejr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--y-cjqQqv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9ij4fjn8kkhf0c1bejr.png" alt="searching client side libraries using LibMan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can even choose the specific version of the library or framework you are interested in as shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VANyPNU3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99p5qc6vyaqv88bnxdfp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VANyPNU3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99p5qc6vyaqv88bnxdfp.png" alt="choosing different versions of client side libraries in LibMan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you will select the version you need, the tool will also give you the option to download all or specific files, and finally, you can specify the location where you want to download the packages and libraries in your project. In ASP.NET Core projects, &lt;strong&gt;wwwroot&lt;/strong&gt; folder is normally used to save client side CSS and JavaScript libraries so you can keep the default location and press the &lt;strong&gt;Install&lt;/strong&gt; button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mYV8Xiwa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kbx3hcec616uchdblzn7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mYV8Xiwa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kbx3hcec616uchdblzn7.png" alt="choose and download specific client library files using LibMan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once the package is installed, you will see that the selected files are downloaded and saved inside wwwroot folder. Secondly, you will also see a new file &lt;strong&gt;libman.json&lt;/strong&gt; is added in your project. This file is similar to package.json file we saw above. It will be used to keep track of all third party libraries and packages you are downloading in your project using the LibMan tool.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VfUe65Tn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5meum8x70vf97y47x7dh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VfUe65Tn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5meum8x70vf97y47x7dh.png" alt="specific files downloaded using LibMan"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What is NuGet&lt;/strong&gt;?
&lt;/h2&gt;

&lt;p&gt;While npm is a package manager for client side libraries and frameworks, &lt;a href="https://docs.microsoft.com/en-us/nuget/"&gt;NuGet&lt;/a&gt; is a package manager to create, share, and consume server side code and libraries in the .NET world. Developers can&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Bundle their code (DLLs) and related resources into packages (.nupkg files)&lt;/li&gt;
&lt;li&gt;Publish their NuGet packages to a private host (exclusive to an organization) or a public repository of packages such as nuget.org&lt;/li&gt;
&lt;li&gt;Search, download, and consume packages hosted by other developers&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Using NuGet from PowerShell Command Line (CLI)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;You can download NuGet packages in your project using the &lt;strong&gt;dotnet&lt;/strong&gt; tool ‘&lt;strong&gt;add package&lt;/strong&gt;’ command. For example, if you want to download a famous Newtonsoft.Json library, you can use the following command in the command window.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet add package Newtonsoft.Json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the package is downloaded, you will notice that it is added as a dependency under a “&lt;strong&gt;Packages&lt;/strong&gt;” node in Solution Explorer. If you will open the project file, you will also notice that its reference is also added as the &lt;strong&gt;PackageReference&lt;/strong&gt; element.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Yv2zVqTp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myzn8deq8w98kvetzl17.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Yv2zVqTp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myzn8deq8w98kvetzl17.png" alt="nuget package using dotnet cli"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to delete the Newtonsoft package from your project, you simply need to remove the &lt;strong&gt;PackageReference&lt;/strong&gt; element from your project file and build your project.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Using NuGet from Package Manager Console (CLI)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If you don’t want to use the PowerShell command window mentioned above and want to stay within Visual Studio then you can find and download NuGet packages from the &lt;strong&gt;NuGet Package Manager Console&lt;/strong&gt; available in Visual Studio. This console allows you to find, install, uninstall, or update NuGet packages using CLI commands. Please note that this console is built into Visual Studio on Windows. It is not included with Visual Studio for Mac or Visual Studio Code. You can open this console using the &lt;strong&gt;Tools&lt;/strong&gt; &amp;gt; &lt;strong&gt;NuGet Package Manager&lt;/strong&gt; &amp;gt; &lt;strong&gt;Package Manager Console&lt;/strong&gt; command in Visual Studio. Once the console is open, you can find packages with the &lt;strong&gt;Find-Package&lt;/strong&gt; command as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Find-Package elmah
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will be able to see all packages with the word ‘elmah’ in the console window.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XA3LKhs0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1quxiqqok3g5fg9vczjo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XA3LKhs0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1quxiqqok3g5fg9vczjo.png" alt="searching nuget package using package manager console"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To install a specific package in your project, you can use the ‘&lt;strong&gt;Install-Package&lt;/strong&gt;’ command with the package name you want to download.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Install-Package elmah
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make sure when you are using the above command, the &lt;strong&gt;‘nuget.exe’&lt;/strong&gt; is selected as a &lt;strong&gt;Package source&lt;/strong&gt; and your project is showing in the &lt;strong&gt;Default project&lt;/strong&gt; dropdown.&lt;/p&gt;

&lt;p&gt;To check the full list of NuGet commands, you can visit &lt;a href="https://docs.microsoft.com/en-us/nuget/reference/powershell-reference"&gt;Nuget PowerShell Commands&lt;/a&gt; page in Microsoft official docs.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Using NuGet Package Manager UI in Visual Studio&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If you don’t want to remember or learn NuGet command, then you can use the Nuget Package Manager UI available in Visual Studio on Windows. The UI interface allows you to easily search, install, uninstall, and update NuGet packages in either one project or all the projects of the solutions with ease. To open the NuGet Package Manager UI, simply Right click on your project in Solution Explorer and choose “&lt;strong&gt;Manage NuGet Packages…&lt;/strong&gt;” option.&lt;/p&gt;

&lt;p&gt;By default, the NuGet UI will display the list of most popular NuGet packages but you can search for the package you need by typing the package name in the search box. You can also select the Package source to tell the UI from where you want to download and install the packages. Once you have the package in the list, selecting the package will display its description, available versions, and dependencies on the right hand side. You can choose the version you need and click the “&lt;strong&gt;Install&lt;/strong&gt;” button to start the installation process.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--R-PR8MQA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2s0oniqoxhy6iz9drenv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--R-PR8MQA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2s0oniqoxhy6iz9drenv.png" alt="searching and installing nuget package using visual studio"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To learn more about the Package Manager UI you can visit the official docs &lt;a href="https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Summary&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;There are millions of third party packages available for client and server side development and I hope this tutorial has given ASP.NET Core developers an overview of the different tools and extensions you can use to search and install the third party package and library you love. Please share your feedback about this tutorial and my blog in general in the comments section.&lt;/p&gt;

</description>
      <category>aspnetcore</category>
      <category>packages</category>
      <category>node</category>
      <category>nuget</category>
    </item>
  </channel>
</rss>
