The flow of this article
- Angular Project Introduction
- Installation
- Database
- Create MVC Web Application
- Adding Model into the Application
- Adding the Web API Controller to the Application
- Create the Angular Service
- Creating Angular Components
- Defining route and navigation menu for our Application
- 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
- CREATETABLE tblEmployee (
- EmployeeID int IDENTITY(1, 1) NOT NULL PRIMARYKEY,
- Namevarchar(20) NOT NULL,
- City varchar(20) NOT NULL,
- Department varchar(20) NOT NULL,
- Gender varchar(6) NOT NULL
- ) GO CREATETABLE tblCities (
- CityID int IDENTITY(1, 1) NOT NULL PRIMARYKEY,
- 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.
- INSERTINTO tblCities
- VALUES
- ('Surat');
- INSERTINTO tblCities
- VALUES
- ('Mumbai');
- INSERTINTO tblCities
- VALUES
- ('Amreli');
- INSERTINTO tblCities
- VALUES
- ('Vadodara');
- INSERTINTO tblCities
- VALUES
- (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.
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.
Open EmployeeDataAccessLayer.cs and put the following code to handle database operations like list insert update and also delete opration.
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace EFNgApp.Models {
- public class EmployeeDataAccessLayer {
- Angular5_core2Context db = new Angular5_core2Context();
- public IEnumerable < TblEmployee > GetAllEmployee() {
- try {
- return db.TblEmployee.ToList();
- } catch {
- throw;
- }
- }
-
- public int AddEmployee(TblEmployee employee) {
- try {
- db.TblEmployee.Add(employee);
- db.SaveChanges();
- return 1;
- } catch {
- throw;
- }
- }
-
- public int UpdateEmployee(TblEmployee employee) {
- try {
- db.Entry(employee).State = EntityState.Modified;
- db.SaveChanges();
- return 1;
- } catch {
- throw;
- }
- }
-
- public TblEmployee GetEmployeeData(int id) {
- try {
- TblEmployee employee = db.TblEmployee.Find(id);
- return employee;
- } catch {
- throw;
- }
- }
-
- public int DeleteEmployee(int id) {
- try {
- TblEmployee emp = db.TblEmployee.Find(id);
- db.TblEmployee.Remove(emp);
- db.SaveChanges();
- return 1;
- } catch {
- throw;
- }
- }
-
- public List < TblCities > GetCities() {
- List < TblCities > lstCity = new List < TblCities > ();
- lstCity = (from CityList in db.TblCities select CityList).ToList();
- return lstCity;
- }
- }
- }
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.
Open EmployeeController.csfile 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 > Get() {
- return objemployee.GetAllEmployee();
- }
- [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();
- }
- }
- }
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.
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.
- import {
- Injectable,
- Inject
- } from '@angular/core';
- import {
- Http,
- Response
- } from '@angular/http';
- import {
- Observable
- } from 'rxjs/Observable';
- import {
- Router
- } from '@angular/router';
- import 'rxjs/add/operator/map';
- import 'rxjs/add/operator/catch';
- import 'rxjs/add/observable/throw';
- @Injectable()
- export class EmpserviceService {
- myAppUrl: string = "";
- constructor(private _http: Http, @Inject('BASE_URL') baseUrl: string) {
- this.myAppUrl = baseUrl;
- }
- getCityList() {
- return this._http.get(this.myAppUrl + 'api/Employee/GetCityList').map(res => res.json()).catch(this.errorHandler);
- }
- getEmployees() {
- return this._http.get(this.myAppUrl + 'api/Employee/Index').map((response: Response) => response.json()).catch(this.errorHandler);
- }
- getEmployeeById(id: number) {
- return this._http.get(this.myAppUrl + "api/Employee/Details/" + id).map((response: Response) => response.json()).catch(this.errorHandler)
- }
- saveEmployee(employee) {
- return this._http.post(this.myAppUrl + 'api/Employee/Create', employee).map((response: Response) => response.json()).catch(this.errorHandler)
- }
- updateEmployee(employee) {
- return this._http.put(this.myAppUrl + 'api/Employee/Edit', employee).map((response: Response) => response.json()).catch(this.errorHandler);
- }
- deleteEmployee(id) {
- return this._http.delete(this.myAppUrl + "api/Employee/Delete/" + id).map((response: Response) => response.json()).catch(this.errorHandler);
- }
- errorHandler(error: Response) {
- console.log(error);
- return Observable.throw(error);
- }
- }
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.
-
fetchemployee component - to display all the employee data and delete an existing employee data.
-
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
Now, our ClientApp/app/components will look like the image below.
Now, open add-employee.component.ts file and put the following code into it.
- import {
- Component,
- OnInit
- } from '@angular/core';
- import {
- Http,
- Headers
- } from '@angular/http';
- import {
- NgForm,
- FormBuilder,
- FormGroup,
- Validators,
- FormControl
- } from '@angular/forms';
- import {
- Router,
- ActivatedRoute
- } from '@angular/router';
- import {
- FetchEmployeeComponent
- } from '../fetch-employee/fetch-employee.component';
- import {
- EmpserviceService
- } from '../../services/empservice.service';
- @Component({
- selector: 'app-add-employee',
- templateUrl: './add-employee.component.html',
- styleUrls: ['./add-employee.component.css']
- })
- export class AddEmployeeComponent implements OnInit {
- employeeForm: FormGroup;
- title: string = "Create";
- employeeId: number;
- errorMessage: any;
- cityList: Array < any > = [];
- constructor(private _fb: FormBuilder, private _avRoute: ActivatedRoute, private _employeeService: EmpserviceService, private _router: Router) {
- if (this._avRoute.snapshot.params["id"]) {
- this.employeeId = this._avRoute.snapshot.params["id"];
- }
- this.employeeForm = this._fb.group({
- employeeId: 0,
- name: ['', [Validators.required]],
- gender: ['', [Validators.required]],
- department: ['', [Validators.required]],
- city: ['', [Validators.required]]
- })
- }
- ngOnInit() {
- this._employeeService.getCityList().subscribe(data => this.cityList = data)
- if (this.employeeId > 0) {
- this.title = "Edit";
- this._employeeService.getEmployeeById(this.employeeId).subscribe(resp => this.employeeForm.setValue(resp), error => this.errorMessage = error);
- }
- }
- save() {
- if (!this.employeeForm.valid) {
- return;
- }
- if (this.title == "Create") {
- this._employeeService.saveEmployee(this.employeeForm.value).subscribe((data) => {
- this._router.navigate(['/fetch-employee']);
- }, error => this.errorMessage = error)
- } else if (this.title == "Edit") {
- this._employeeService.updateEmployee(this.employeeForm.value).subscribe((data) => {
- this._router.navigate(['/fetch-employee']);
- }, error => this.errorMessage = error)
- }
- }
- cancel() {
- this._router.navigate(['/fetch-employee']);
- }
- get name() {
- return this.employeeForm.get('name');
- }
- get gender() {
- return this.employeeForm.get('gender');
- }
- get department() {
- return this.employeeForm.get('department');
- }
- get city() {
- return this.employeeForm.get('city');
- }
- }
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.
- <h1>{{title}}</h1>
- <h3>Employee</h3>
- <hr />
- <form [formGroup]="employeeForm" (ngSubmit)="save()" #formDir="ngForm" novalidate>
- <div class="form-group row"> <label class=" control-label col-md-12">Name</label>
- <div class="col-md-4"> <input class="form-control" type="text" formControlName="name"> </div> <span class="text-danger" *ngIf="name.invalid && formDir.submitted">
- Name is required.
- </span> </div>
- <div class="form-group row"> <label class="control-label col-md-12" for="Gender">Gender</label>
- <div class="col-md-4"> <select class="form-control" data-val="true" formControlName="gender">
- <option value="">-- Select Gender --</option>
- <option value="Male">Male</option>
- <option value="Female">Female</option>
- </select> </div> <span class="text-danger" *ngIf="gender.invalid && formDir.submitted">
- Gender is required
- </span> </div>
- <div class="form-group row"> <label class="control-label col-md-12" for="Department">Department</label>
- <div class="col-md-4"> <input class="form-control" type="text" formControlName="department"> </div> <span class="text-danger" *ngIf="department.invalid && formDir.submitted">
- Department is required
- </span> </div>
- <div class="form-group row"> <label class="control-label col-md-12" for="City">City</label>
- <div class="col-md-4"> <select class="form-control" data-val="true" formControlName="city">
- <option value="">--Select City--</option>
- <option *ngFor="let city of cityList"
- value={{city.cityName}}>
- {{city.cityName}}
- </option>
- </select> </div> <span class="text-danger" *ngIf="city.invalid && formDir.submitted">
- City is required
- </span> </div>
- <div class="form-group"> <button type="submit" class="btn btn-default">Save</button> <button class="btn" (click)="cancel()">Cancel</button> </div>
- </form>
Open fetch-employee.component.ts file and put the following code to it.
- import {
- Component,
- Inject
- } from '@angular/core';
- import {
- Http,
- Headers
- } from '@angular/http';
- import {
- Router,
- ActivatedRoute
- } from '@angular/router';
- import {
- EmpserviceService
- } from '../../services/empservice.service'
- @Component({
- selector: 'app-fetch-employee',
- templateUrl: './fetch-employee.component.html',
- styleUrls: ['./fetch-employee.component.css']
- })
- export class FetchEmployeeComponent {
- public empList: EmployeeData[];
- constructor(public http: Http, private _router: Router, private _employeeService: EmpserviceService) {
- this.getEmployees();
- }
- getEmployees() {
- this._employeeService.getEmployees().subscribe(data => this.empList = data)
- }
- delete(employeeID) {
- var ans = confirm("Do you want to delete customer with Id: " + employeeID);
- if (ans) {
- this._employeeService.deleteEmployee(employeeID).subscribe((data) => {
- this.getEmployees();
- }, error => console.error(error))
- }
- }
- }
- interface EmployeeData {
- employeeId: number;
- name: string;
- gender: string;
- city: string;
- department: string;
- }
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.
- import {
- NgModule
- } from '@angular/core';
- import {
- EmpserviceService
- } from './services/empservice.service'
- import {
- CommonModule
- } from '@angular/common';
- import {
- FormsModule,
- ReactiveFormsModule
- } from '@angular/forms';
- import {
- HttpModule
- } from '@angular/http';
- import {
- RouterModule
- } from '@angular/router';
- import {
- AddEmployeeComponent
- } from './components/add-employee/add-employee.component';
- import {
- FetchEmployeeComponent
- } from './components/fetch-employee/fetch-employee.component';
- import {
- HomeComponent
- } from './home/home.component';
- import {
- NavMenuComponent
- } from './nav-menu/nav-menu.component';
- import {
- AppComponent
- } from './app.component';
- import {
- BrowserModule
- } from '@angular/platform-browser';
- @NgModule({
- declarations: [
- AppComponent,
- NavMenuComponent,
- HomeComponent,
- AddEmployeeComponent,
- FetchEmployeeComponent
- ],
- imports: [
- BrowserModule.withServerTransition({
- appId: 'ng-cli-universal'
- }),
- CommonModule,
- HttpModule,
- FormsModule,
- ReactiveFormsModule,
- RouterModule.forRoot([{
- path: '',
- component: HomeComponent,
- pathMatch: 'full'
- }, {
- path: 'home',
- component: HomeComponent
- }, {
- path: 'fetch-employee',
- component: FetchEmployeeComponent
- }, {
- path: 'add-employee',
- component: AddEmployeeComponent
- }, {
- path: 'employee/edit/:id',
- component: AddEmployeeComponent
- }, {
- path: '**',
- redirectTo: 'home'
- }])
- ],
- providers: [EmpserviceService],
- bootstrap: [AppComponent]
- })
- 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.
- <div class='main-nav'>
- <div class='navbar navbar-inverse'>
- <div class='navbar-header'> <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse' [attr.aria-expanded]='isExpanded' (click)='toggle()'>
- <span class='sr-only'>Toggle navigation</span>
- <span class='icon-bar'></span>
- <span class='icon-bar'></span>
- <span class='icon-bar'></span>
- </button> <a class='navbar-brand' [routerLink]='["/"]'>EFNgApp</a> </div>
- <div class='clearfix'></div>
- <div class='navbar-collapse collapse' [ngClass]='{ "in": isExpanded }'>
- <ul class='nav navbar-nav'>
- <li [routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'> <a [routerLink]='["/"]' (click)='collapse()'>
- <span class='glyphicon glyphicon-home'></span> Home
- </a> </li>
- <li [routerLinkActive]='["link-active"]'> <a [routerLink]='["/add-employee"]' (click)='collapse()'>
- <span class='glyphicon glyphicon-education'></span> Add Employee
- </a> </li>
- <li [routerLinkActive]='["link-active"]'> <a [routerLink]='["/fetch-employee"]' (click)='collapse()'>
- <span class='glyphicon glyphicon-th-list'></span> Fetch Employee
- </a> </li>
- </ul>
- </div>
- </div>
- </div>
Run your application
Press F5 to launch the application.
Now, insert the employee data with proper validation.
Source Code
You can get the source code from GitHub.