Introduction:

In this article we will learn how to complete CURD (Create, Read, Update and Delete operation in asp.net core MVC with Entity framework.

Description:

This is part one of the series of Database First Approach with ASP.NET Core MVC. In this article, I will demonstrate you about Database First Approach in Entity Framework and will also show how to implement it with ASP.NET Core  MVC. With that I will show you how to make CRUD (Create, Read, Update and Delete) operation functionality in ASP.NET Core MVC.  
What is Database First Approach
There are the following approach which is used to connect with database to application.

  •         Database First
  •         Model First
  •         Code First

Today, we will learn about Database First Approach. So, first question comes in the mind “What is Database First”. So, Database First is nothing but only a approach to create web application where database is available first and can interact with database. In this database, database is created first and after that we manage the code. The Entity Framework is able to generate a business model based on the tables and columns in a relational database.

So, you need to create your database first in SQL Server.  

To create a new database first open “Microsoft SQL Server Management Studio” and right click on Database node and choose

 New Database.

Open New Query window and execute the following code in query window:

create database TechMindCore

 

Create a table in Database  like below:

 CREATE TABLE Movie
(
ID bigint primary key identity(1,1),
Title  nvarchar(100),
ReleaseDate  DateTime,
Genre  nvarchar(100),
Price Decimal(10,2)
)

 

Now Open Visual Studio 2017 and let’s create a new ASP.NET Core Web Application project. to do this, Select File > New > Project. In the New Project dialog select Visual C# > Web > ASP.NET Core Web Application just like in the figure below:   

crud operations in asp.net core using entity framework core database first  

Figure 1: ASP.NET Core Web Application Project Template 

             

Name your project to whatever you like, but for this exercise, we will name it as “AspDotNetCoreMvc” to confirm with the topic. Click OK and then select “Web Application (Model-View-Controller)” within ASP.NET Core templates as shown in the following figure below:

crud operations in asp.net core using entity framework core database first

Figure 2: ASP.NET Core Web Application Template

 

Now click on Change Authentication box.

Select the individual User Accounts options and then click the OK button to let Visual Studio generate the required files needed for us to run the application. The figure below shows the default generated files:

crud operations in asp.net core using entity framework core database first

Figure 3: The Models ,Views and Controller

 

Now, open the appsettings.json file and provide the database name, database server name, and related credentials to establish the connection with the database.

{
  "ConnectionStrings": {
    "DefaultConnection": "Password=sa@123;Persist Security Info=True;User ID=sa;Initial Catalog=TechMindCore;Data Source=(local)"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Integrating Entity Framework Core

Now, in order to import existing database context object using entity framework to my core web application, I need to install the following library packages via "Tools->NuGet Package Manager->Manage NuGet Packages for Solution".

Now, right-click on the root of your application and then select Manage NuGet Packages. Select the Browse tab and in the search bar, type in “Microsoft.EntityFrameworkCore.SqlServer”. It should result to something like this:

crud operations in asp.net core using entity framework core database first

Figure 4: Manage NuGet Package

 we are going to use Database-First development approach to work with existing database, we need to   install the additional packages below as well:

        ·         Microsoft.EntityFrameworkCore.Tools (v2.0.1)

        ·         Microsoft.EntityFrameworkCore.SqlServer.Design (v1.1.4)

 

Using Nuget Package Manager GUI

Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution, then type in "Microsoft.EntityFrameworkCore.Tools”. Click install just like in the figure below:

crud operations in asp.net core using entity framework core database first

Figure 5: Adding Microsoft.EntityFrameworkCore.Tools package

When it’s done installing all the required packages, you should be able to see them added to your project dependencies as shown in the figure below:

crud operations in asp.net core using entity framework core database first

Figure 6: Entity Framework Core Packages installed 

 

        Creating Entity Models from Existing Database Using Package Manager Console

        Now Click "Tools->NuGet Package Manager->Package Manager Console" as shown below:


         crud operations in asp.net core using entity framework core database first

Figure 7: Console Manager Package

 

 

Type the following command inside the console as shown below.

 

Scaffold-DbContext "Server=(local);Database=TechMindCore;Trusted_Connection=True;user id=sa;password=sa@123;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DataBase

 crud operations in asp.net core using entity framework core database first

Figure 8: Console Manager Package window

 

The Server attribute above is the SQL server instance name. You can find it in SQL Management Studio by right clicking on your database. For this example, the server name is “(local)”.

The Database attribute is your database name. In this case, the database name is “TechMindCore”.

The –OutputDir attribute allows you to specify the location of the files generated. In this case, we’ve set it to Models/DataBase.

The command above will generate models from existing database within Models/DB folder. Here’s the screenshot below:

crud operations in asp.net core using entity framework core database first

Figure 9: database context object Output.

 

Now see above highlighted File “TechMindCoreContext.cs” DbContext Generated successfully.

Creating View and Controller

The next step is to create UI. In this step, I have created Controller and various required View. I have “MovieController.cs” file under the Controllers folder and created two Views under the “Views” folder. Following snap is showing the hierarchy of folders and files within our project.

crud operations in asp.net core using entity framework core database first

Figure 10: ASP.NET Core controller and view 

 

Following is the code snippet for MovieController.
MovieController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models.DataBase;
namespace WebApplication1.Controllers
{
    public class MovieController: Controller
    {
        TechMindCoreContext db = new TechMindCoreContext();
        public IActionResult Index()
        {
            return View(db.Movie.ToList());
 
        }
 
        public IActionResult Create()
        {
 
            return View();
        }
            [HttpPost]
        public IActionResult Create(Movie model)
        {
            if (model.Id <= 0 )
            {
                db.Movie.Add(model);
            }
            else
            {
                var movie = db.Movie.FirstOrDefault(x => x.Id == model.Id);
                movie.Title = model.Title;
                movie.Price= model.Price;
                movie.Genre= model.Genre;
               movie.ReleaseDate = model.ReleaseDate;
            }
           db.SaveChanges();
            returnRedirectToAction("Index", "Movie");
 
        }
 
        public IActionResult Edit(long id)
        {
 
            Movie mov =db.Movie.FirstOrDefault(x => x.Id == id);
            return View("Create",mov);
        }
        public IActionResult Delete(long id)
        {
            Movie mov = db.Movie.FirstOrDefault(x => x.Id == id);
           db.Movie.Remove(mov);
           db.SaveChanges();
            returnRedirectToAction("Index", "Movie");
        }
    }
}


Index view (Initial List View)
It is the entry point of the application. Following is the code snippet for index View.
Index.cshtml

@model IEnumerable<WebApplication1.Models.DataBase.Movie>
 
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Movie List</h2>
 
<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model=> model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model=> model.Title)
                </th>
                <th>
                    @Html.DisplayNameFor(model=> model.ReleaseDate)
                </th>
                <th>
                    @Html.DisplayNameFor(model=> model.Genre)
                </th>
                <th>
                    @Html.DisplayNameFor(model=> model.Price)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem=> item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.ReleaseDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Genre)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Price)
            </td>
            <td>
                @Html.ActionLink("Edit","Edit", new { id=item.Id  })              
                @Html.ActionLink("Delete","Delete", new {  id=item.Id  })
            </td>
        </tr>
}
    </tbody>
</table>
 

 

 

Create add /edit view

Now, I am defining the "Add/Edit" View. The following is the code snippet for "Create.cshtml".

Create.cshtml
 

@model WebApplication1.Models.DataBase.Movie
 
@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
   
}
 
<h2>Create/Edit Movie</h2>
<h4>Movie</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">               
                <input asp-for="Id" class="form-control" type="hidden" />               
            </div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReleaseDate" class="control-label"></label>
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>
 
<div>
    <a asp-action="Index">Back to List</a>
</div>
 
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
 

Now build and run the application using CTRL + 5. In the browser, navigate to /movie. It should bring up the following page.

crud operations in asp.net core using entity framework core database first

Figure 11: Movie List

 

If you want to create new movie click on create New button then open new window which is show in the figure below:

crud operations in asp.net core using entity framework core database first

Figure 12: Create New Movie

 

If you want to Edit movie Record click on Edit button then open new window as shown in the figure below:

crud operations in asp.net core using entity framework core database first

Figure 13: Edit Movie

 

If you want to Delete movie Record click on Delete button record will delete.


Now, in this article, we learn the Crud operation step by step in ASP.NET Core. I hope, this will help the readers to understand how to complete curd operation in asp.net mvc core.



Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like