ASP.NET Core With Entity Framework

Kailash Chandra Behera | Sunday, June 28, 2020

Introduction

In the blog ASP.NET Core With Entity Framework, we will learn how to make database entity connection in asp net core and how to use entity framework database first module.

Getting Started

The ASP.NET Core MVC framework is a lightweight, open source, highly testable presentation framework optimized for use with ASP.NET Core.

ASP.NET Core MVC provides a patterns-based way to build dynamic websites that enables a clean separation of concerns. It gives you full control over markup, supports TDD-friendly development, and uses the latest web standards.

What is the MVC pattern?

The Model-View-Controller (MVC) architectural pattern separates an application into three main groups of components: Models, Views, and Controllers. This pattern helps to achieve separation of concerns. Using this pattern, user requests are routed to a Controller which is responsible for working with the Model to perform user actions and/or retrieve results of queries. The Controller chooses the View to display to the user, and provides it with any Model data it requires.

Demonstration

Here in the demonstration, we will create a ASP.NET Core MVC application and will perform CRUD operation in the application. we will also create model, view and controller and will create separate action method in controller for each CRUD operation.

Using MVC, Entity Framework, and ASP.NET Core Scaffolding, we will create a web application that provides an interface to an existing database. This demonstration shows you how to automatically generate code that enables users to display, edit, create, and delete data that resides in a database table.

To store data from view to database, we will use here the SQL server 2017 and the entity framework database first approach. This database first approach creates models from the database.

I have posted a blog where I have demonstrated how to create ASP.NET Core MVC application and publish the application, refer to the blog, you will get the idea how to create the ASP.NET Core MVC template then follow below steps to use entity framework for CRUD operation.

Steps for ASP.NET Core With Entity Framework

  1. Open The SQL Server and create a database with named "Test".

  2. Create a table named "employee" with columns such as (Code as Numeric datathype, ID as string, Name as string and Department as string).

  3. Go to my blog, referred in the above and create ASP.NET Core MVC template.

  4. Go to the Solution Explorer of Visual Studio and right-click on the model folder. Then go to "Add" -> "New Item". The Add New Item Window will open, select ADO.NET Entity Data Model. Rename the entity data model to test, than press "Ok".

  5. Select "Generate from database" from the Entity Data Model Wizard Window and press "Next", select an existing connection to create a new connection. Then press the "Next" button.

  6. Select the table or tables, if required rename the model name, then press "Ok"; the selected table will appear in the test.edmx file.

  7. Again go to the Solution Explorer, right-click on the Controllers folder, click "Add Controller". In the Add Controller window rename the controller to "Empcontroller", select the option "Add action for Create, Update, Delete and Detail Scenario". Then press "Add".

  8. The EmpController class will appear in the Visual Studio. Create the object of the entity class that you created when you created the model in the constructor of controller. The code is given below.

     //Create the object of testentities class  
     Models.testEntities TE = new Models.testEntities();  
    
  9. Build the application, so the employee model class will appear while creating the view for your application.

  10. In the EmpController, you will find index action method. Add the below code and your index method should look like below code.

     public ActionResult Index()  
     {  
       //Querying to the employee table  
       List<Models.Employee> emp = TE.Employees.ToList();  
       //Passing employee list to view as a paramenter  
       return View(emp);  
     }  
    
  11. Then right-click on the index function and select "Add View", rename that view if required. Select "Create a Strongly-typed View" than select "Employee Model", then select Scaffold template as to list. Than press "Add".

  12. Copy the below Details method code and replace with the Detailsaction method in the EmpController and add View to this method.

     public ActionResult Details(int id)  
     {  
       Models.Employee emp = TE.Employees.Where(x => x.Code == id).Single();  
       return View(emp);  
     }  
    

  13. Replace the Create post method with the below code and view for this action method, this action method is used to create or add employee details into database.

     [HttpPost]  
     public ActionResult Create(Models.Employee emp)  
     {  
       try  
       {  
         TE.Connection.Open();  
         TE.Employees.AddObject(emp);  
         TE.SaveChanges();  
         TE.AcceptAllChanges();  
         return RedirectToAction("Index");  
       }  
       catch  
       {  
         return View();  
       }  
     }  
    
  14. Create a view for Edit action method and write the following code inside the Edit method.

     public ActionResult Edit(int id)  
     {  
       TE.Connection.Open();  
       //Querying to the employee table  
       Models.Employee emp = TE.Employees.Where(x => x.Code == id).Single();  
       return View(emp);  
     }  
     // POST: /Emp/Edit/5  
     [HttpPost]  
     public ActionResult Edit(int id, Models.Employee emp)  
     {  
       Try  
       {  
           // TODO: Add update logic here  
           Models.Employee emp1 = TE.Employees.Where(x => x.Code == id).Single();  
           emp1.Name=emp.Name;  
           emp1.Department=emp.Department;  
           TE.AcceptAllChanges();  
           TE.SaveChanges();  
           return RedirectToAction("Index");  
       }  
       Catch  
       {  
          return View();  
       }  
     }  
    
  15. For the delete operation, replace the below code with appropriate code.

     public ActionResult Delete(int id)  
     {  
        Models.Employee emp = TE.Employees.Where(x => x.Code == id).Single();  
        return View(emp);  
     }  
     // POST: /Emp/Delete/5  
     [HttpPost]  
     public ActionResult Delete(int id, FormCollection collection)  
     {  
       try  
       {  
          // TODO: Add delete logic here  
          Models.Employee emp = TE.Employees.Where(x => x.Code == id).Single();  
          TE.Employees.DeleteObject(emp);  
          TE.SaveChanges();  
          TE.AcceptAllChanges();  
          return RedirectToAction("Index");  
       }  
       Catch  
       {  
         return View();  
       }  
     }  
    
  16. Now you are done with ASP.NET Core With Entity Framework. Run the application and redirect to EmpController index method

Related Articles

  1. Create an ASP.NET Core Application in Azure
  2. Create an MVC Application in Azure
  3. Creating Application in Prism
  4. WPF Application using MVVM In C#
  5. Bootstrapper for Prism Application
  6. Creating a simple ASP.NET Web Service
  7. AngularJS CRUD Operation
  8. Creating an AngularJS Application

Summary

Using MVC, Entity Framework, and ASP.NET Core Scaffolding, we created a web application that provides an interface to an existing database. in demonstration(ASP.NET Core With Entity Framework) we saw how to automatically generate code that enables users to display, edit, create, and delete data that resides in a database table. I hope you enjoyed it a lot.

Thanks