How To Perform CRUD Operation In Angular With .NET Core Using Entity Framework

The flow of this article

  1. Angular Project Introduction
  2. Installation
  3. Database
  4. Create MVC Web Application
  5. Adding Model into the Application
  6. Adding the Web API Controller to the Application
  7. Create the Angular Service
  8. Creating Angular Components
  9. Defining route and navigation menu for our Application
  10. Running your application

Angular Project Introduction

today  we learn How To Perform CRUD Operation In Angular With .NET Core Using Entity Framework using ASP.NET Core 2.1 and Angular 5 with the help  of  vs2017, Entity Framework Core database first approach.

Installation

  • Install .NET Core 2.1 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.
Database

Create one database named like Angular5_core2 and create two tables

  1. CREATETABLE tblEmployee (  
  2.   EmployeeID int IDENTITY(1, 1) NOT NULL PRIMARYKEY,   
  3.   Namevarchar(20) NOT NULL,   
  4.   City varchar(20) NOT NULL,   
  5.   Department varchar(20) NOT NULL,   
  6.   Gender varchar(6) NOT NULL  
  7. ) GO CREATETABLE tblCities (  
  8.   CityID int IDENTITY(1, 1) NOT NULL PRIMARYKEY,   
  9.   CityName varchar(20) NOT NULL  
  10. ) 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.

  1. INSERTINTO tblCities   
  2. VALUES   
  3.   ('Surat');  
  4. INSERTINTO tblCities   
  5. VALUES   
  6.   ('Mumbai');  
  7. INSERTINTO tblCities   
  8. VALUES   
  9.   ('Amreli');  
  10. INSERTINTO tblCities   
  11. VALUES   
  12.   ('Vadodara');  
  13. INSERTINTO tblCities   
  14. VALUES   
  15.   (Bharuch);  

Create MVC Web Application

  • Open Visual Studio and select File  New  Project than Select .NET Core 2.1  than  select “ASP.NET Core Web Application” from available project types. Put the name of the project as EFNgApp and press OK.

    .NET Core 2.1 
  • then select the .net core 2.1 and press ok.

    .NET Core
  • your project is created now see the structure of this project

    .NET Core

Adding the Model to the Application

  • open package manager consoler and write some command.
    • Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.1.0-preview1-final
    • Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.1.0-preview1-final

  • 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.

Now your model will be created successfully..
 
Right click on Models folder and select add class EmployeeDataAccessLayer.cs
your structure will be display like this.
 
.NET Core

Open EmployeeDataAccessLayer.cs and put the following code to handle database operations like list insert update and also delete opration.

  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. namespace EFNgApp.Models {  
  7.     public class EmployeeDataAccessLayer {  
  8.         Angular5_core2Context db = new Angular5_core2Context();  
  9.         public IEnumerable < TblEmployee > GetAllEmployee() {  
  10.             try {  
  11.                 return db.TblEmployee.ToList();  
  12.             } catch {  
  13.                 throw;  
  14.             }  
  15.         }  
  16.         //To Add new employee record  
  17.         public int AddEmployee(TblEmployee employee) {  
  18.             try {  
  19.                 db.TblEmployee.Add(employee);  
  20.                 db.SaveChanges();  
  21.                 return 1;  
  22.             } catch {  
  23.                 throw;  
  24.             }  
  25.         }  
  26.         //To Update the records of a particluar employee  
  27.         public int UpdateEmployee(TblEmployee employee) {  
  28.             try {  
  29.                 db.Entry(employee).State = EntityState.Modified;  
  30.                 db.SaveChanges();  
  31.                 return 1;  
  32.             } catch {  
  33.                 throw;  
  34.             }  
  35.         }  
  36.         //Get the details of a particular employee  
  37.         public TblEmployee GetEmployeeData(int id) {  
  38.             try {  
  39.                 TblEmployee employee = db.TblEmployee.Find(id);  
  40.                 return employee;  
  41.             } catch {  
  42.                 throw;  
  43.             }  
  44.         }  
  45.         //To Delete the record of a particular employee  
  46.         public int DeleteEmployee(int id) {  
  47.             try {  
  48.                 TblEmployee emp = db.TblEmployee.Find(id);  
  49.                 db.TblEmployee.Remove(emp);  
  50.                 db.SaveChanges();  
  51.                 return 1;  
  52.             } catch {  
  53.                 throw;  
  54.             }  
  55.         }  
  56.         //To Get the list of Cities  
  57.         public List < TblCities > GetCities() {  
  58.             List < TblCities > lstCity = new List < TblCities > ();  
  59.             lstCity = (from CityList in db.TblCities select CityList).ToList();  
  60.             return lstCity;  
  61.         }  
  62.     }  

Adding the Web API Controller to the Application

Right click on Controllers folder and controller then select the “Web API Controller Class” from templates panel and put the name as EmployeeController.cs. Press OK.

.NET Core 

Open EmployeeController.csfile and put the following code into it.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using EFNgApp.Models;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
  8. namespace EFNgApp.Controllers {  
  9.     public class EmployeeController: Controller {  
  10.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  11.         [HttpGet]  
  12.         [Route("api/Employee/Index")]  
  13.         public IEnumerable < TblEmployee > Get() {  
  14.                 return objemployee.GetAllEmployee();  
  15.             }  
  16.             [HttpPost]  
  17.             [Route("api/Employee/Create")]  
  18.         public int Create([FromBody] TblEmployee employee) {  
  19.                 return objemployee.AddEmployee(employee);  
  20.             }  
  21.             [HttpGet]  
  22.             [Route("api/Employee/Details/{id}")]  
  23.         public TblEmployee Details(int id) {  
  24.                 return objemployee.GetEmployeeData(id);  
  25.             }  
  26.             [HttpPut]  
  27.             [Route("api/Employee/Edit")]  
  28.         public int Edit([FromBody] TblEmployee employee) {  
  29.                 return objemployee.UpdateEmployee(employee);  
  30.             }  
  31.             [HttpDelete]  
  32.             [Route("api/Employee/Delete/{id}")]  
  33.         public int Delete(int id) {  
  34.                 return objemployee.DeleteEmployee(id);  
  35.             }  
  36.             [HttpGet]  
  37.             [Route("api/Employee/GetCityList")]  
  38.         public IEnumerable < TblCities > Details() {  
  39.             return objemployee.GetCities();  
  40.         }  
  41.     }  
  42. }  

Create the Angular Service

We will create an Angular service which will convert the Web API response to JSON and pass it to our component.

Right-click on ClientApp/app folder and then Add  New Folder and name the folder as Services.
  • Now, open the command prompt with service location path and write the command for making a new service using CLI.

    .NET Core 
Ng generate service empservice --spec=false

--spec=false tells the system to not to create spec.ts file because we don't need it.

Open empservice.service.ts file and put the following code into it.

  1. import {  
  2.     Injectable,  
  3.     Inject  
  4. } from '@angular/core';  
  5. import {  
  6.     Http,  
  7.     Response  
  8. } from '@angular/http';  
  9. import {  
  10.     Observable  
  11. } from 'rxjs/Observable';  
  12. import {  
  13.     Router  
  14. } from '@angular/router';  
  15. import 'rxjs/add/operator/map';  
  16. import 'rxjs/add/operator/catch';  
  17. import 'rxjs/add/observable/throw';  
  18. @Injectable()  
  19. export class EmpserviceService {  
  20.     myAppUrl: string = "";  
  21.     constructor(private _http: Http, @Inject('BASE_URL') baseUrl: string) {  
  22.         this.myAppUrl = baseUrl;  
  23.     }  
  24.     getCityList() {  
  25.         return this._http.get(this.myAppUrl + 'api/Employee/GetCityList').map(res => res.json()).catch(this.errorHandler);  
  26.     }  
  27.     getEmployees() {  
  28.         return this._http.get(this.myAppUrl + 'api/Employee/Index').map((response: Response) => response.json()).catch(this.errorHandler);  
  29.     }  
  30.     getEmployeeById(id: number) {  
  31.         return this._http.get(this.myAppUrl + "api/Employee/Details/" + id).map((response: Response) => response.json()).catch(this.errorHandler)  
  32.     }  
  33.     saveEmployee(employee) {  
  34.         return this._http.post(this.myAppUrl + 'api/Employee/Create', employee).map((response: Response) => response.json()).catch(this.errorHandler)  
  35.     }  
  36.     updateEmployee(employee) {  
  37.         return this._http.put(this.myAppUrl + 'api/Employee/Edit', employee).map((response: Response) => response.json()).catch(this.errorHandler);  
  38.     }  
  39.     deleteEmployee(id) {  
  40.         return this._http.delete(this.myAppUrl + "api/Employee/Delete/" + id).map((response: Response) => response.json()).catch(this.errorHandler);  
  41.     }  
  42.     errorHandler(error: Response) {  
  43.         console.log(error);  
  44.         return Observable.throw(error);  
  45.     }  
  46. }  

Creating Angular Components

Make the new folder in Clientapp/src/app and give the name as Components.

We will be adding two Angular components to our application.

  1. fetchemployee component - to display all the employee data and delete an existing employee data.

  2. addemployee component - to add a new employee data or edit an existing employee data.

Now, open cmd with your component directory and write the command like that.

ng g c add-employee --spec=false

After the complete process of this command, write command for the fetch-employee component

ng g c fetch-employee --spec=false

g=generate

c=component

.NET Core

Now, our ClientApp/app/components will look like the image below.
 
.NET Core
 
Now, open add-employee.component.ts file and put the following code into it.
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     Http,  
  7.     Headers  
  8. } from '@angular/http';  
  9. import {  
  10.     NgForm,  
  11.     FormBuilder,  
  12.     FormGroup,  
  13.     Validators,  
  14.     FormControl  
  15. } from '@angular/forms';  
  16. import {  
  17.     Router,  
  18.     ActivatedRoute  
  19. } from '@angular/router';  
  20. import {  
  21.     FetchEmployeeComponent  
  22. } from '../fetch-employee/fetch-employee.component';  
  23. import {  
  24.     EmpserviceService  
  25. } from '../../services/empservice.service';  
  26. @Component({  
  27.     selector: 'app-add-employee',  
  28.     templateUrl: './add-employee.component.html',  
  29.     styleUrls: ['./add-employee.component.css']  
  30. })  
  31. export class AddEmployeeComponent implements OnInit {  
  32.     employeeForm: FormGroup;  
  33.     title: string = "Create";  
  34.     employeeId: number;  
  35.     errorMessage: any;  
  36.     cityList: Array < any > = [];  
  37.     constructor(private _fb: FormBuilder, private _avRoute: ActivatedRoute, private _employeeService: EmpserviceService, private _router: Router) {  
  38.         if (this._avRoute.snapshot.params["id"]) {  
  39.             this.employeeId = this._avRoute.snapshot.params["id"];  
  40.         }  
  41.         this.employeeForm = this._fb.group({  
  42.             employeeId: 0,  
  43.             name: ['', [Validators.required]],  
  44.             gender: ['', [Validators.required]],  
  45.             department: ['', [Validators.required]],  
  46.             city: ['', [Validators.required]]  
  47.         })  
  48.     }  
  49.     ngOnInit() {  
  50.         this._employeeService.getCityList().subscribe(data => this.cityList = data)  
  51.         if (this.employeeId > 0) {  
  52.             this.title = "Edit";  
  53.             this._employeeService.getEmployeeById(this.employeeId).subscribe(resp => this.employeeForm.setValue(resp), error => this.errorMessage = error);  
  54.         }  
  55.     }  
  56.     save() {  
  57.         if (!this.employeeForm.valid) {  
  58.             return;  
  59.         }  
  60.         if (this.title == "Create") {  
  61.             this._employeeService.saveEmployee(this.employeeForm.value).subscribe((data) => {  
  62.                 this._router.navigate(['/fetch-employee']);  
  63.             }, error => this.errorMessage = error)  
  64.         } else if (this.title == "Edit") {  
  65.             this._employeeService.updateEmployee(this.employeeForm.value).subscribe((data) => {  
  66.                 this._router.navigate(['/fetch-employee']);  
  67.             }, error => this.errorMessage = error)  
  68.         }  
  69.     }  
  70.     cancel() {  
  71.         this._router.navigate(['/fetch-employee']);  
  72.     }  
  73.     get name() {  
  74.         return this.employeeForm.get('name');  
  75.     }  
  76.     get gender() {  
  77.         return this.employeeForm.get('gender');  
  78.     }  
  79.     get department() {  
  80.         return this.employeeForm.get('department');  
  81.     }  
  82.     get city() {  
  83.         return this.employeeForm.get('city');  
  84.     }  
  85. }  

This component will be used for both adding and editing the employee data. Now, open add-employee.component.html file and put the following code into it.

  1. <h1>{{title}}</h1>  
  2. <h3>Employee</h3>  
  3. <hr />  
  4. <form [formGroup]="employeeForm" (ngSubmit)="save()" #formDir="ngForm" novalidate>  
  5.     <div class="form-group row"> <label class=" control-label col-md-12">Name</label>  
  6.         <div class="col-md-4"> <input class="form-control" type="text" formControlName="name"> </div> <span class="text-danger" *ngIf="name.invalid && formDir.submitted">  
  7. Name is required.  
  8. </span> </div>  
  9.     <div class="form-group row"> <label class="control-label col-md-12" for="Gender">Gender</label>  
  10.         <div class="col-md-4"> <select class="form-control" data-val="true" formControlName="gender">  
  11. <option value="">-- Select Gender --</option>  
  12. <option value="Male">Male</option>  
  13. <option value="Female">Female</option>  
  14. </select> </div> <span class="text-danger" *ngIf="gender.invalid && formDir.submitted">  
  15. Gender is required  
  16. </span> </div>  
  17.     <div class="form-group row"> <label class="control-label col-md-12" for="Department">Department</label>  
  18.         <div class="col-md-4"> <input class="form-control" type="text" formControlName="department"> </div> <span class="text-danger" *ngIf="department.invalid && formDir.submitted">  
  19. Department is required  
  20. </span> </div>  
  21.     <div class="form-group row"> <label class="control-label col-md-12" for="City">City</label>  
  22.         <div class="col-md-4"> <select class="form-control" data-val="true" formControlName="city">  
  23. <option value="">--Select City--</option>  
  24. <option *ngFor="let city of cityList"  
  25. value={{city.cityName}}>  
  26. {{city.cityName}}  
  27. </option>  
  28. </select> </div> <span class="text-danger" *ngIf="city.invalid && formDir.submitted">  
  29. City is required  
  30. </span> </div>  
  31.     <div class="form-group"> <button type="submit" class="btn btn-default">Save</button> <button class="btn" (click)="cancel()">Cancel</button> </div>  
  32. </form>  

Open fetch-employee.component.ts file and put the following code to it.

  1. import {  
  2.     Component,  
  3.     Inject  
  4. } from '@angular/core';  
  5. import {  
  6.     Http,  
  7.     Headers  
  8. } from '@angular/http';  
  9. import {  
  10.     Router,  
  11.     ActivatedRoute  
  12. } from '@angular/router';  
  13. import {  
  14.     EmpserviceService  
  15. } from '../../services/empservice.service'  
  16. @Component({  
  17.     selector: 'app-fetch-employee',  
  18.     templateUrl: './fetch-employee.component.html',  
  19.     styleUrls: ['./fetch-employee.component.css']  
  20. })  
  21. export class FetchEmployeeComponent {  
  22.     public empList: EmployeeData[];  
  23.     constructor(public http: Http, private _router: Router, private _employeeService: EmpserviceService) {  
  24.         this.getEmployees();  
  25.     }  
  26.     getEmployees() {  
  27.         this._employeeService.getEmployees().subscribe(data => this.empList = data)  
  28.     }  
  29.     delete(employeeID) {  
  30.         var ans = confirm("Do you want to delete customer with Id: " + employeeID);  
  31.         if (ans) {  
  32.             this._employeeService.deleteEmployee(employeeID).subscribe((data) => {  
  33.                 this.getEmployees();  
  34.             }, error => console.error(error))  
  35.         }  
  36.     }  
  37. }  
  38. interface EmployeeData {  
  39.     employeeId: number;  
  40.     name: string;  
  41.     gender: string;  
  42.     city: string;  
  43.     department: string;  
  44. }  

Defining route and navigation menu for our Application

Now, add the path of your component in app.module.ts file. Open app.module.tsfile and put the following code into it.

  1. import {  
  2.     NgModule  
  3. } from '@angular/core';  
  4. import {  
  5.     EmpserviceService  
  6. } from './services/empservice.service'  
  7. import {  
  8.     CommonModule  
  9. } from '@angular/common';  
  10. import {  
  11.     FormsModule,  
  12.     ReactiveFormsModule  
  13. } from '@angular/forms';  
  14. import {  
  15.     HttpModule  
  16. } from '@angular/http';  
  17. import {  
  18.     RouterModule  
  19. } from '@angular/router';  
  20. import {  
  21.     AddEmployeeComponent  
  22. } from './components/add-employee/add-employee.component';  
  23. import {  
  24.     FetchEmployeeComponent  
  25. } from './components/fetch-employee/fetch-employee.component';  
  26. import {  
  27.     HomeComponent  
  28. } from './home/home.component';  
  29. import {  
  30.     NavMenuComponent  
  31. } from './nav-menu/nav-menu.component';  
  32. import {  
  33.     AppComponent  
  34. } from './app.component';  
  35. import {  
  36.     BrowserModule  
  37. } from '@angular/platform-browser';  
  38. @NgModule({  
  39.     declarations: [  
  40.         AppComponent,  
  41.         NavMenuComponent,  
  42.         HomeComponent,  
  43.         AddEmployeeComponent,  
  44.         FetchEmployeeComponent  
  45.     ],  
  46.     imports: [  
  47.         BrowserModule.withServerTransition({  
  48.             appId: 'ng-cli-universal'  
  49.         }),  
  50.         CommonModule,  
  51.         HttpModule,  
  52.         FormsModule,  
  53.         ReactiveFormsModule,  
  54.         RouterModule.forRoot([{  
  55.             path: '',  
  56.             component: HomeComponent,  
  57.             pathMatch: 'full'  
  58.         }, {  
  59.             path: 'home',  
  60.             component: HomeComponent  
  61.         }, {  
  62.             path: 'fetch-employee',  
  63.             component: FetchEmployeeComponent  
  64.         }, {  
  65.             path: 'add-employee',  
  66.             component: AddEmployeeComponent  
  67.         }, {  
  68.             path: 'employee/edit/:id',  
  69.             component: AddEmployeeComponent  
  70.         }, {  
  71.             path: '**',  
  72.             redirectTo: 'home'  
  73.         }])  
  74.     ],  
  75.     providers: [EmpserviceService],  
  76.     bootstrap: [AppComponent]  
  77. })  
  78. export class AppModule {}  

Here, we have also imported all our components and defined the route for our application as below.

  • home - which will redirect to home component
  • fetch-employee - to display all employee data using fetch-employee component
  • add-employee - to add new employee record using add-employee component
  • employee/edit/:id - to edit existing employee record using add-employee component

One last thing is to define the navigation menu for our application. Open /app/components/navmenu/navmenu.component.html file and put the following code to it.

  1. <div class='main-nav'>  
  2.     <div class='navbar navbar-inverse'>  
  3.         <div class='navbar-header'> <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse' [attr.aria-expanded]='isExpanded' (click)='toggle()'>  
  4. <span class='sr-only'>Toggle navigation</span>  
  5. <span class='icon-bar'></span>  
  6. <span class='icon-bar'></span>  
  7. <span class='icon-bar'></span>  
  8. </button> <a class='navbar-brand' [routerLink]='["/"]'>EFNgApp</a> </div>  
  9.         <div class='clearfix'></div>  
  10.         <div class='navbar-collapse collapse' [ngClass]='{ "in": isExpanded }'>  
  11.             <ul class='nav navbar-nav'>  
  12.                 <li [routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'> <a [routerLink]='["/"]' (click)='collapse()'>  
  13. <span class='glyphicon glyphicon-home'></span> Home  
  14. </a> </li>  
  15.                 <li [routerLinkActive]='["link-active"]'> <a [routerLink]='["/add-employee"]' (click)='collapse()'>  
  16. <span class='glyphicon glyphicon-education'></span> Add Employee  
  17. </a> </li>  
  18.                 <li [routerLinkActive]='["link-active"]'> <a [routerLink]='["/fetch-employee"]' (click)='collapse()'>  
  19. <span class='glyphicon glyphicon-th-list'></span> Fetch Employee  
  20. </a> </li>  
  21.             </ul>  
  22.         </div>  
  23.     </div>  
  24. </div>  

Run your application

Press F5 to launch the application.

.NET Core

.NET Core

Now, insert the employee data with proper validation.

.NET Core

Source Code

You can get the source code from GitHub.