Skip to main content

ASP.Net Core MVC Project Part 4

In this article we will add Entity Framework support in project and we will also create database from domain classes using nuget commands. This article is fourth part of Asp.Net Core MVC project series. Please read article ASP.Net Core MVC Project Part 3 before reading this article.

Entity Framework Core

Entity Framework is ORM i.e. Object Relational Mapper. It maps classes and properties to database tables and fields. We can access and manipulate tables and its fields without writing SQL code. We could use SQL statements but it is not necessary as Entity Framework allows us to use LINQ statements. Entity Framework Core only supports code first approach that means first we have to create domain classes and properties and these will be mapped to database tables and fields. So we need to create domain classes first then we need to create database context class i.e. DbContext.

DbContext Class

DbContext class is important for working with Entity Framework Core.It connects code with database.It keeps track of all data changes and it persists changes back to database. DbContext uses DbSet property to work with entities. DbSet represents a particular table in the database.

Connection String

We need connection string to connect with database. It is stored in appsettings.json file in the project.

We need to modify Startup class to use Entity Framework in our project, we also need to add packages of Entity Framework Core in our project.

Entity Framework Core Packages

Now we will install Entity Framework Core package using nuget.We are using the same project as discussed in previous article. Open the project and right click on Dependencies and select ‘Manage Nuget Packages’ as shown in below screenshot:

After clicking on ‘Manage Nuget Packages’ below screen will appear , click on Browse tab and search for Microsoft.EntityFrameworkCore.SqlServer package. Select highlighted package and click on install button.

Click on OK to accept terms and conditions popup. After that install package ‘Microsoft.EntityFrameworkCore’ using the same steps as mentioned above. Also install ‘Microsoft.EntityFrameworkCore.Tools’ package.

AppDbContext Class

We have installed necessary packages, now we will add class for DbContext. Right click on Models folder and add new class , class name is AppDbContext. Please see below screenshot:

Class AppDbContext will inherit DbContext class, this class is defined in Microsoft.EntityFrameworkCore namespace so you need to import this namespace. For AppDbContext , we need to pass some options in its constructor. Option will be of Type DbContextOptions. Below is the code:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace eShop.Models
{
    public class AppDbContext:DbContext
    {
     public AppDbContext(DbContextOptions<AppDbContext> options):
           base(options)
      {

      }
    }
}

Now we will add DbSet for managing entities. We are adding 2 DbSet as shown below:

public class AppDbContext:DbContext
 {
    public AppDbContext(DbContextOptions options):base(options)
    {    
    }
    DbSet<Product> Products { get; set; }
    DbSet<Category> Categories { get; set; }

}

Now we have AppDbContext and DbSet properties for Product and Catgory entities for managing the entities. Now we will see the steps for connecting to database.

Database Connectivity

Connection string is stored in appsettings.json file. Below is the content of appsettings.json file which contains connection string:

{
  "ConnectionStrings": {
    "DefaultConnection": "Database=eShopProjectDb;Server=LAPTOP-C6S52PEG\\SQL20141;Uid=sa;Pwd=123;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Please note database name is ‘eShopProjectDb’ which does not exist yet. Connection string also contains database server name and credentials to connect to this database. You can provide details of your local database server details.

Register Entity Framework Core

We have connection string ready, now we have to register Entity Framework Core in Startup.cs file so that it can be used for database connectivity. Below is the existing Startup.cs file which we have modified in article ‘ASP.Net Core MVC Project Part 2‘:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }
        
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
        endpoints.MapControllerRoute(
            name:"default",
            pattern:"{controller=Home}/{action=Index}/{id?}"
            );
        });
    }
}

First we will do required changes for reading connection string, add a read only property Configuration of type IConfiguration. IConfiguration exists in namespace ‘Microsoft.Extensions.Configuration’ so we have to import this namespace.

 public IConfiguration Configuration { get;}

Now we have to inject Configuration property in constructor so that we can use this. Configuration property can read connection string from appsettings.json file.

       public IConfiguration Configuration { get;}
        public Startup(IConfiguration configurationParam)
        {
            Configuration = configurationParam;
        }

Now we will change ConfigureServices() method . Below is the code:

public IConfiguration Configuration { get;}
public Startup(IConfiguration configurationParam)
{
 Configuration = configurationParam;
}
public void ConfigureServices(IServiceCollection services)
{
 services.AddDbContext<AppDbContext>(options=> options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
 services.AddControllersWithViews();
}

In ConfigureServices() method, we have added a service for connecting to database and we have passed options which indicates that we will use SQL Server and we have read connection string from appsettings.json inside options.UseSqlServer().

Now we have changed ConfigureServices() method to use Entity Framework Core for database connectivity. Below is the complete Startup.cs file:

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using eShop.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace eShop
{
public class Startup
{
    public IConfiguration Configuration { get;}
    public Startup(IConfiguration configurationParam)
    {
     Configuration = configurationParam;
    }
    public void ConfigureServices(IServiceCollection services)
    {
  services.AddDbContext<AppDbContext>(options=>  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")) 
   );
    services.AddControllersWithViews();
    }
        
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
    endpoints.MapControllerRoute(
        name:"default",
        pattern:"{controller=Home}/{action=Index}/{id?}"
        );
    });
  }
 }
}

Database Migration

Now we will create database. Click on Tools menu and from Nuget Package Manager , select package manager console

In package manager console, write command add-migration for creating initial migration and press enter key.

Add-Migration command has created Migrations folder in the project:

It has also added a class InitialMigration.cs under Migrations folder:

public partial class InitialMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
    CategoryId = table.Column<int>(nullable: false)
        .Annotation("SqlServer:Identity", "1, 1"),
    CategoryName = table.Column<string>(nullable: true),
    CategoryDescription = table.Column<string>(nullable: true)
},
constraints: table =>
{
    table.PrimaryKey("PK_Categories", x => x.CategoryId);
});

migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
    ProductId = table.Column<int>(nullable: false)
        .Annotation("SqlServer:Identity", "1, 1"),
    Name = table.Column<string>(nullable: true),
    Description = table.Column<string>(nullable: true),
    Price = table.Column<decimal>(nullable: false),
    ImageUrl = table.Column<string>(nullable: true),
    ImageThumbnailUrl = table.Column<string>(nullable: true),
    IsOnSale = table.Column<bool>(nullable: false),
    IsInStock = table.Column<bool>(nullable: false),
    CategoryId = table.Column<int>(nullable: false)
},
constraints: table =>
{
    table.PrimaryKey("PK_Products", x => x.ProductId);
    table.ForeignKey(
        name: "FK_Products_Categories_CategoryId",
        column: x => x.CategoryId,
        principalTable: "Categories",
        principalColumn: "CategoryId",
        onDelete: ReferentialAction.Cascade);
});

migrationBuilder.CreateIndex(
name: "IX_Products_CategoryId",
table: "Products",
column: "CategoryId");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Products");

migrationBuilder.DropTable(
name: "Categories");
}
}

Now open package manager console again and write command update-database, this command will run Up() method of InitialMigration.cs class and database will be created.

This command has now created the database. You can verify this by connecting SQL Server using SQL Server Management Studio.

In this article we have seen enabling Entity Framework Core support in the project. We will implement repositories in next article.

Download code from below URL:
https://github.com/vijendra-ksh/eShop

Below are list of previous articles in this project series :

a) ASP.Net Core MVC Project Part 1
b) ASP.Net Core MVC Project Part 2
c) ASP.Net Core MVC Project Part 3

Please like our Facebook page for getting updates about new articles :
https://www.facebook.com/logixn

Leave a Reply

Your email address will not be published. Required fields are marked *