Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ASP.NET Core - CRUD Using Angular 5 and Entity Framework Core, Part 1

DZone's Guide to

ASP.NET Core - CRUD Using Angular 5 and Entity Framework Core, Part 1

In Part 1 of this two-part series, we begin building our full stack web application, concentrating on getting the backend of the app up and running.

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

In this article series, we are going to create a web application using ASP.NET Core 2.0 and Angular 5 with the help of Entity Framework Core's database first approach. We will be creating a sample Employee Record Management system. To read the inputs from the user, we are using Angular Forms with required field validations on the client side. We are also going to bind a dropdown list in the Angular Form to a table in the database using EF Core.

We will be using Visual Studio 2017 and SQL Server 2012.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2017 Community Edition from here.
  • Download and install the latest version of Node.js from here.
  • SQL Server 2008 or above.

Source Code

Before proceeding I would recommend you to get the source code from GitHub.

Creating Some Tables

We will be using two tables to store our data.

  1. tblEmployee: Used to store the details of employee. It contains fields such as EmployeeID, Name, City, Department, and Gender.
  2. tblCities: - This contains the list of cities and used to populate the City field of tblEmployee table. It contains two fields CityID and CityName.

Execute the following commands to create both tables:

CREATE TABLE tblEmployee (  
EmployeeID int IDENTITY(1,1) NOT NULL PRIMARY KEY,  
Name varchar(20) NOT NULL ,  
City varchar(20) NOT NULL ,  
Department varchar(20) NOT NULL ,  
Gender varchar(6) NOT NULL   
)  
GO  

CREATE TABLE tblCities (  
CityID int IDENTITY(1,1) NOT NULL PRIMARY KEY,  
CityName varchar(20) NOT NULL   
)  
GO  

Now, we will put some data into the tblCities table. We will be using this table to bind a dropdown list in our web application from which the desired city can be selected. Use the following insert statements.

INSERT INTO tblCities VALUES('New Delhi');  
INSERT INTO tblCities VALUES('Mumbai');  
INSERT INTO tblCities VALUES('Hyderabad');  
INSERT INTO tblCities VALUES('Chennai');  
INSERT INTO tblCities VALUES('Bengaluru');

Now, our database part has been completed. So, we will proceed to create the MVC application using Visual Studio 2017.

Create an MVC Web Application

Open Visual Studio and select File >> New >> Project.

After selecting the project, a "New Project" dialog will open. Select .NET Core inside Visual C# menu from the left panel.

Then, select "ASP.NET Core Web Application" from the available project types. Set the name of the project as EFNgApp and press OK.

After clicking on OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select ".NET Core" and "ASP.NET Core 2.0" from these dropdowns. Then, select "Angular" template and press OK.

Now, our project will be created. You can observe the folder structure in Solution Explorer as shown in the below image.

Here, we have our Controllers and Views folders. We won't be touching the Views folders for this tutorial since we will be using Angular to handle the UI. The Controllers folders will contain our Web API controller. The point of interest for us is the ClientApp folder where the client side of our application resides. Inside the ClientApp/app/components folder, we already have a few components created which are provided by default with the Angular template in VS 2017. These components won't affect our application, but for the sake of this tutorial, we will delete fetchdata and counter folders from ClientApp/app/components.

Adding the Model to the Application

We are using Entity Framework core database first approach to create our models. Navigate to Tools >> NuGet Package Manager >> Package Manager Console.

We have to install the package for the database provider that we are targeting which is SQL Server in this case. Hence, run the following command:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Since we are using Entity Framework Tools to create a model from the existing database, we will install the tools package as well. Hence, run the following command:

Install-Package Microsoft.EntityFrameworkCore.Tools

After you have installed both the packages, we will scaffold our model from the database tables using the following command:

Scaffold-DbContext "Your connection string here" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables tblEmployee, tblCities

Do not forget to put your own connection string (inside " "). After this command gets executed successfully, you will see that a Models folder has been created and it contains three class files myTestDBContext.cs, TblCities.cs, and TblEmployee.cs. And hence we have successfully created our Models using EF core database first approach.

Now, we will create one more class file to handle database related operations.

Right click on Models folder and select Add >> Class. Name your class EmployeeDataAccessLayer.csand click Add button. At this point in time, the Models folder will have the following structure.

Open EmployeeDataAccessLayer.cs and put the following code to handle database operations.

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

namespace EFNgApp.Models  
{  
    public class EmployeeDataAccessLayer  
    {  
        myTestDBContext db = new myTestDBContext();  

        public IEnumerable<TblEmployee> GetAllEmployees()  
        {  
            try  
            {  
                return db.TblEmployee.ToList();  
            }  
            catch  
            {  
                throw;  
            }  
        }  

        //To Add new employee record   
        public int AddEmployee(TblEmployee employee)  
        {  
            try  
            {  
                db.TblEmployee.Add(employee);  
                db.SaveChanges();  
                return 1;  
            }  
            catch  
            {  
                throw;  
            }  
        }  

        //To Update the records of a particluar employee  
        public int UpdateEmployee(TblEmployee employee)  
        {  
            try  
            {  
                db.Entry(employee).State = EntityState.Modified;  
                db.SaveChanges();  

                return 1;  
            }  
            catch  
            {  
                throw;  
            }  
        }  

        //Get the details of a particular employee  
        public TblEmployee GetEmployeeData(int id)  
        {  
            try  
            {  
                TblEmployee employee = db.TblEmployee.Find(id);  
                return employee;  
            }  
            catch  
            {  
                throw;  
            }  
        }  

        //To Delete the record of a particular employee  
        public int DeleteEmployee(int id)  
        {  
            try  
            {  
                TblEmployee emp = db.TblEmployee.Find(id);  
                db.TblEmployee.Remove(emp);  
                db.SaveChanges();  
                return 1;  
            }  
            catch  
            {  
                throw;  
            }  
        }  

        //To Get the list of Cities  
        public List<TblCities> GetCities()  
        {  
            List<TblCities> lstCity = new List<TblCities>();  
            lstCity = (from CityList in db.TblCities select CityList).ToList();  

            return lstCity;  
        }  
    }  
}

Now, we will proceed to create our Web API Controller.

Adding the Web API Controller to the Application

Right click on Controllers folder and select Add >> New Item.

An "Add New Item" dialog box will open. Select ASP.NET from the left panel, then select "Web API Controller Class" from the templates panel and set the name as EmployeeController.cs. Press OK.

This will create our Web API EmployeeController class. We will put all our business logic in this controller. We will call the methods of EmployeeDataAccessLayer to fetch data and pass on the data to the Angular frontend.

Open the EmployeeController.cs file and put the following code into it.

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

namespace EFNgApp.Controllers  
{  

    public class EmployeeController : Controller  
    {  
        EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  

        [HttpGet]  
        [Route("api/Employee/Index")]  
        public IEnumerable<TblEmployee> Index()  
        {  
            return objemployee.GetAllEmployees();  
        }  

        [HttpPost]  
        [Route("api/Employee/Create")]  
        public int Create([FromBody] TblEmployee employee)  
        {  
            return objemployee.AddEmployee(employee);  
        }  

        [HttpGet]  
        [Route("api/Employee/Details/{id}")]  
        public TblEmployee Details(int id)  
        {  
            return objemployee.GetEmployeeData(id);  
        }  

        [HttpPut]  
        [Route("api/Employee/Edit")]  
        public int Edit([FromBody]TblEmployee employee)  
        {  
            return objemployee.UpdateEmployee(employee);  
        }  

        [HttpDelete]  
        [Route("api/Employee/Delete/{id}")]  
        public int Delete(int id)  
        {  
            return objemployee.DeleteEmployee(id);  
        }  

        [HttpGet]  
        [Route("api/Employee/GetCityList")]  
        public IEnumerable<TblCities> Details()  
        {  
            return objemployee.GetCities();  
        }  
    }  
}

We are done with our backend logic. So, we will now proceed to code our frontend using Angular 5.

Tune in next tomorrow to build the front-end of our application!

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:
asp.net core 2.0 ,angular 5 ,entity framework core ,web dev ,crud

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}