ASP.NET Core - CRUD Using Angular 5 And Entity Framework Core

Introduction

In this article, we are going to create a web application using ASP.NET Core 2.0 and Angular 5 with the help of Entity Framework Core 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 also learn how to deploy this application on IIS.

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 Table

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

  1. CREATE TABLE tblEmployee (  
  2. EmployeeID int IDENTITY(1,1) NOT NULL PRIMARY KEY,  
  3. Name varchar(20) NOT NULL ,  
  4. City varchar(20) NOT NULL ,  
  5. Department varchar(20) NOT NULL ,  
  6. Gender varchar(6) NOT NULL   
  7. )  
  8. GO  
  9.   
  10. CREATE TABLE tblCities (  
  11. CityID int IDENTITY(1,1) NOT NULL PRIMARY KEY,  
  12. CityName varchar(20) NOT NULL   
  13. )  
  14. 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. INSERT INTO tblCities VALUES('New Delhi');  
  2. INSERT INTO tblCities VALUES('Mumbai');  
  3. INSERT INTO tblCities VALUES('Hyderabad');  
  4. INSERT INTO tblCities VALUES('Chennai');  
  5. 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 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 available project types. Put 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 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:
  1. 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:

  1. 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:
  1. 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 can observe 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.cs and click Add button. At this point of time, the Models folder will have the following structure.

 
Open EmployeeDataAccessLayer.cs and put the following code to handle database operations.
  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace EFNgApp.Models  
  8. {  
  9.     public class EmployeeDataAccessLayer  
  10.     {  
  11.         myTestDBContext db = new myTestDBContext();  
  12.   
  13.         public IEnumerable<TblEmployee> GetAllEmployees()  
  14.         {  
  15.             try  
  16.             {  
  17.                 return db.TblEmployee.ToList();  
  18.             }  
  19.             catch  
  20.             {  
  21.                 throw;  
  22.             }  
  23.         }  
  24.   
  25.         //To Add new employee record   
  26.         public int AddEmployee(TblEmployee employee)  
  27.         {  
  28.             try  
  29.             {  
  30.                 db.TblEmployee.Add(employee);  
  31.                 db.SaveChanges();  
  32.                 return 1;  
  33.             }  
  34.             catch  
  35.             {  
  36.                 throw;  
  37.             }  
  38.         }  
  39.   
  40.         //To Update the records of a particluar employee  
  41.         public int UpdateEmployee(TblEmployee employee)  
  42.         {  
  43.             try  
  44.             {  
  45.                 db.Entry(employee).State = EntityState.Modified;  
  46.                 db.SaveChanges();  
  47.   
  48.                 return 1;  
  49.             }  
  50.             catch  
  51.             {  
  52.                 throw;  
  53.             }  
  54.         }  
  55.   
  56.         //Get the details of a particular employee  
  57.         public TblEmployee GetEmployeeData(int id)  
  58.         {  
  59.             try  
  60.             {  
  61.                 TblEmployee employee = db.TblEmployee.Find(id);  
  62.                 return employee;  
  63.             }  
  64.             catch  
  65.             {  
  66.                 throw;  
  67.             }  
  68.         }  
  69.   
  70.         //To Delete the record of a particular employee  
  71.         public int DeleteEmployee(int id)  
  72.         {  
  73.             try  
  74.             {  
  75.                 TblEmployee emp = db.TblEmployee.Find(id);  
  76.                 db.TblEmployee.Remove(emp);  
  77.                 db.SaveChanges();  
  78.                 return 1;  
  79.             }  
  80.             catch  
  81.             {  
  82.                 throw;  
  83.             }  
  84.         }  
  85.   
  86.         //To Get the list of Cities  
  87.         public List<TblCities> GetCities()  
  88.         {  
  89.             List<TblCities> lstCity = new List<TblCities>();  
  90.             lstCity = (from CityList in db.TblCities select CityList).ToList();  
  91.   
  92.             return lstCity;  
  93.         }  
  94.     }  
  95. }  

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 templates panel and put 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 EmployeeController.cs file 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.   
  8. namespace EFNgApp.Controllers  
  9. {  
  10.   
  11.     public class EmployeeController : Controller  
  12.     {  
  13.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  14.   
  15.         [HttpGet]  
  16.         [Route("api/Employee/Index")]  
  17.         public IEnumerable<TblEmployee> Index()  
  18.         {  
  19.             return objemployee.GetAllEmployees();  
  20.         }  
  21.   
  22.         [HttpPost]  
  23.         [Route("api/Employee/Create")]  
  24.         public int Create([FromBody] TblEmployee employee)  
  25.         {  
  26.             return objemployee.AddEmployee(employee);  
  27.         }  
  28.   
  29.         [HttpGet]  
  30.         [Route("api/Employee/Details/{id}")]  
  31.         public TblEmployee Details(int id)  
  32.         {  
  33.             return objemployee.GetEmployeeData(id);  
  34.         }  
  35.   
  36.         [HttpPut]  
  37.         [Route("api/Employee/Edit")]  
  38.         public int Edit([FromBody]TblEmployee employee)  
  39.         {  
  40.             return objemployee.UpdateEmployee(employee);  
  41.         }  
  42.   
  43.         [HttpDelete]  
  44.         [Route("api/Employee/Delete/{id}")]  
  45.         public int Delete(int id)  
  46.         {  
  47.             return objemployee.DeleteEmployee(id);  
  48.         }  
  49.   
  50.         [HttpGet]  
  51.         [Route("api/Employee/GetCityList")]  
  52.         public IEnumerable<TblCities> Details()  
  53.         {  
  54.             return objemployee.GetCities();  
  55.         }  
  56.     }  
  57. }  

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

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.

Right click on Sevices folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Scripts from the left panel, then select “TypeScript File” from templates panel, and put the name as empservice.service.ts. Press OK

 

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

At this point of time, you might get an error “Parameter 'employee' implicitly has an 'any' type” in empservice.service.ts file.

If you encounter this issue, then add the following line inside tsconfig.json file.

"noImplicitAny": false

Now, we will proceed to create our components. 

Creating Angular 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.
Right click on ClientApp/app/components folder and select Add >> New Folder and name the folder as addemployee.
Right click on addemployee folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Scripts from the left panel, then select “TypeScript File” from templates panel, and put the name as addemployee.component.ts. Press OK. This will add a typescript file inside addemployee folder.

 

Right click on addemployee folder and select Add >> New Item. An “Add New Item” dialog box will open. Select ASP.NET Core from the left panel, then select “HTML Page” from templates panel, and put the name as addemployee.component.html. Press OK. This will add a HTML file inside addemployee folder.

 

Similarly create a fetchemployee folder inside ClientApp/app/components folder and add fetchemployee.component.ts typescript and fetchemployee.component.html HTML file to it. 

Now our ClientApp/app/components will look like the image below: 

 

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

Let’s understand this code. At the very top we have imported Angular modules and EmployeeService references. After this we have @Component decorator to define the template URL for our component.

Inside the FetchEmployeeComponent class we have declared an array variable empList of type EmployeeData where EmployeeData is an interface having the properties same as our TblEmployee Model class. Inside the getEmployees method we are calling the getEmployees method of our service EmployeeService, which will return an array of Employees to be stored in empList variable. The getEmployees method is called inside the constructor so that the employee data will be displayed as the page loads.

Next, we have delete method which accepts employeeID as parameter. This will prompt the user with a confirmation box and if the user selects yes then it will delete the employee with this employeeID.

Open fetchemployee.component.html file and put the following code into it.

  1. <h1>Employee Data</h1>  
  2.   
  3. <p>This component demonstrates fetching Employee data from the server.</p>  
  4.   
  5. <p *ngIf="!empList"><em>Loading...</em></p>  
  6.   
  7. <p>  
  8.     <a [routerLink]="['/register-employee']">Create New</a>  
  9. </p>  
  10.   
  11. <table class='table' *ngIf="empList">  
  12.     <thead>  
  13.         <tr>  
  14.             <th>EmployeeId</th>  
  15.             <th>Name</th>  
  16.             <th>Gender</th>  
  17.             <th>Department</th>  
  18.             <th>City</th>  
  19.         </tr>  
  20.     </thead>  
  21.     <tbody>  
  22.         <tr *ngFor="let emp of empList">  
  23.             <td>{{ emp.employeeId }}</td>  
  24.             <td>{{ emp.name }}</td>  
  25.             <td>{{ emp.gender }}</td>  
  26.             <td>{{ emp.department }}</td>  
  27.             <td>{{ emp.city }}</td>  
  28.             <td>  
  29.             <td>  
  30.                 <a [routerLink]="['/employee/edit/', emp.employeeId]">Edit</a> |  
  31.                 <a [routerLink]="" (click)="delete(emp.employeeId)">Delete</a>  
  32.             </td>  
  33.         </tr>  
  34.     </tbody>  
  35. </table>  

The code for this html file is pretty simple. On the top it has a link to create new employee record and after that it will have a table to display employee data and two links for editing and deleting each employee record.

We are finished with our fetchemployee component.

Now open addemployee.component.ts file and put the following code into it:

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

This component will be used for both adding and editing the employee data. Since we are using a form model along with client-side validation to Add and Edit customer data we have imported classes from @angular/forms. The code to create the form has been put inside the constructor so that the form will be displayed as the page loads.

This component will handle both Add and Edit request. So how will the system will differentiate between both requests? The answer is routing. We need to define two different route parameters, one for Add employee record and another to edit employee record. We will be defining these in app.shared.module.ts file shortly.

We have declared variable title to show on the top of page and variable id to store the employee id passed as the parameter in case of edit request. To read the employee id from the URL we will use ActivatedRoute.snapshot inside the constructor and set the value of variable id.

Inside ngOnInit we are performing two operations
  1. We are fetching the list of cities by calling getCityList method from our service. We will bind the list of cities to a dropdown list in our html page. Since we are calling getCityList method in ngOnInit, the dropdown list will be populated as the page loads.
  2. We will check if the id is set then we will change the title to “Edit”, get the data for that id from our service and populate the fields in our form. The value read from database will be returned as JSON and have all the properties same as we declared in our FormBuilder, hence we use setValue method to populate our form.

The save method will be called on clicking on “Save” button of our form. Based on whether it is an Add operation or an Edit operation it will call the corresponding method from our service and then upon success redirect back to fetch-employee component.

In the last one we have also defined getter functions for the control names of our form to enable client-side validation.

Open addemployee.component.html file and put the following code into it:
  1. <h1>{{title}}</h1>  
  2. <h3>Employee</h3>  
  3. <hr />  
  4.   
  5. <form [formGroup]="employeeForm" (ngSubmit)="save()" #formDir="ngForm" novalidate>  
  6.   
  7.     <div class="form-group row">  
  8.         <label class=" control-label col-md-12">Name</label>  
  9.         <div class="col-md-4">  
  10.             <input class="form-control" type="text" formControlName="name">  
  11.         </div>  
  12.         <span class="text-danger" *ngIf="name.invalid && formDir.submitted">  
  13.             Name is required.  
  14.         </span>  
  15.     </div>  
  16.   
  17.     <div class="form-group row">  
  18.         <label class="control-label col-md-12" for="Gender">Gender</label>  
  19.         <div class="col-md-4">  
  20.             <select class="form-control" data-val="true" formControlName="gender">  
  21.                 <option value="">-- Select Gender --</option>  
  22.                 <option value="Male">Male</option>  
  23.                 <option value="Female">Female</option>  
  24.             </select>  
  25.         </div>  
  26.         <span class="text-danger" *ngIf="gender.invalid && formDir.submitted">  
  27.             Gender is required  
  28.         </span>  
  29.     </div>  
  30.     <div class="form-group row">  
  31.         <label class="control-label col-md-12" for="Department">Department</label>  
  32.         <div class="col-md-4">  
  33.             <input class="form-control" type="text" formControlName="department">  
  34.         </div>  
  35.         <span class="text-danger" *ngIf="department.invalid && formDir.submitted">  
  36.             Department is required  
  37.         </span>  
  38.     </div>  
  39.     <div class="form-group row">  
  40.         <label class="control-label col-md-12" for="City">City</label>  
  41.         <div class="col-md-4">  
  42.             <select class="form-control" data-val="true" formControlName="city">  
  43.                 <option value="">--Select City--</option>  
  44.                 <option *ngFor="let city of cityList"  
  45.                         value={{city.cityName}}>  
  46.                     {{city.cityName}}  
  47.                 </option>  
  48.             </select>  
  49.         </div>  
  50.         <span class="text-danger" *ngIf="city.invalid && formDir.submitted">  
  51.             City is required  
  52.         </span>  
  53.     </div>  
  54.     <div class="form-group">  
  55.         <button type="submit" class="btn btn-default">Save</button>  
  56.         <button class="btn" (click)="cancel()">Cancel</button>  
  57.     </div>  
  58. </form>   

Here you can observe that we have attribute [formGroup]="employeeForm”, which is our defined form group name in addemployee.component.ts file. “(ngSubmit)="save()" will invoke our save method on form submit.

Also, every input control has attribute formControlName="xyz", this is used to bind FormControl to HTML. We have also defined error message for client-side validation check and it will be invoked on form submission only.

For binding the dropdown list we are using the cityList property that we have populated from the tblCities table by calling getCityList method from our service inside ngOnInit method of addemployee.component.ts file.

Defining route and navigation menu for our Application

Open /app/app.shared.module.ts file and put the following code into it.
  1. import { NgModule } from '@angular/core';  
  2. import { EmployeeService } from './services/empservice.service'  
  3. import { CommonModule } from '@angular/common';  
  4. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  5. import { HttpModule } from '@angular/http';  
  6. import { RouterModule } from '@angular/router';  
  7.   
  8. import { AppComponent } from './components/app/app.component';  
  9. import { NavMenuComponent } from './components/navmenu/navmenu.component';  
  10. import { HomeComponent } from './components/home/home.component';  
  11. import { FetchEmployeeComponent } from './components/fetchemployee/fetchemployee.component'  
  12. import { createemployee } from './components/addemployee/AddEmployee.component'  
  13.   
  14. @NgModule({  
  15.     declarations: [  
  16.         AppComponent,  
  17.         NavMenuComponent,  
  18.         HomeComponent,  
  19.         FetchEmployeeComponent,  
  20.         createemployee,  
  21.     ],  
  22.     imports: [  
  23.         CommonModule,  
  24.         HttpModule,  
  25.         FormsModule,  
  26.         ReactiveFormsModule,  
  27.         RouterModule.forRoot([  
  28.             { path: '', redirectTo: 'home', pathMatch: 'full' },  
  29.             { path: 'home', component: HomeComponent },  
  30.             { path: 'fetch-employee', component: FetchEmployeeComponent },  
  31.             { path: 'register-employee', component: createemployee },  
  32.             { path: 'employee/edit/:id', component: createemployee },  
  33.             { path: '**', redirectTo: 'home' }  
  34.         ])  
  35.     ],  
  36.     providers: [EmployeeService]  
  37. })  
  38. export class AppModuleShared {  
  39. }  

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 fetchemployee component
  • register-employee - to add new employee record using createemployee component
  • employee/edit/:id - to edit existing employee record using createemployee component 
One last thing is to define 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'>  
  4.             <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>  
  5.                 <span class='sr-only'>Toggle navigation</span>  
  6.                 <span class='icon-bar'></span>  
  7.                 <span class='icon-bar'></span>  
  8.                 <span class='icon-bar'></span>  
  9.             </button>  
  10.             <a class='navbar-brand' [routerLink]="['/home']">ASPCoreWithAngular</a>  
  11.         </div>  
  12.         <div class='clearfix'></div>  
  13.         <div class='navbar-collapse collapse'>  
  14.             <ul class='nav navbar-nav'>  
  15.                 <li [routerLinkActive]="['link-active']">  
  16.                     <a [routerLink]="['/home']">  
  17.                         <span class='glyphicon glyphicon-home'></span> Home  
  18.                     </a>  
  19.                 </li>  
  20.                 <li [routerLinkActive]="['link-active']">  
  21.                     <a [routerLink]="['/fetch-employee']">  
  22.                         <span class='glyphicon glyphicon-th-list'></span> Fetch employee  
  23.                     </a>  
  24.                 </li>  
  25.             </ul>  
  26.         </div>  
  27.     </div>  
  28. </div>  

And that’s it. We have created our first ASP.NET Core application using Angular 5 and Entity Framework core database first approach.

Execution Demo

Press F5 to launch the application.

A web page will open as shown in the image below. Notice the URL showing route for our home component. And navigation menu on the left showing navigation link for Home and Fetch Employee pages. 


Click on Fetch Employee in the navigation menu. It will redirect to fetch employee component and displays all the employee data on the page. 

 

Since we have not added any data, hence it is empty.

Click on CreateNew to navigate to /register-employee page. Add a new Employee record as shown in the image below. You can observe that the City field is a dropdown list, containing all the city names that we have inserted into tblCities table.

 

If we miss the data in any field while creating employee record, we will get a required field validation error message 

 

After inserting the data in all the fields, click on "Save" button. The new employee record will be created and you will be redirected to the /fetch-employee page, displaying records of all the employees. Here, we can also see action methods Edit and Delete.

 

If we want to edit an existing employee record, then click Edit action link. It will open Edit page as below where we can change the employee data. Notice that we have passed employee id in URL parameter. 
 

Here we have changed the City of employee Rahul from Hyderabad to Chennai. Click on "Save" to return to the fetch-employee page to see the updated changes as highlighted in the image below:

 

If we miss any fields while editing employee records, then Edit view will also throw required field validation error message as shown in the image below:

 

Now, we will perform Delete operation on an employee named Swati having Employee ID 2. Click on Delete action link which will open a JavaScript confirmation box asking for a confirmation to delete.

 

Once we click on Delete button the employee with name Swati will be removed from our record and you can see the updated list of employee as shown below.

 
 
Deploying the application
 
Open tsconfig.json file and add the following line:
 
"strictNullChecks”: false
 
Refer to the image below:
 
 
When we publish the application , Visual Studio will run “node node_modules/webpack/bin/webpack.js –config webpack.config.vendor.js –env.prod” command. Adding the above mentioned line in tsconfig.json file will ensure that this command will not strictly check for any null values in our application.
 
Please note that if you are not publishing this application then you do not need to add “strictNullChecks”: false in your tsconfig.json file.
 
After this follow the same steps mentioned at Deploying a Blazor Application on IIS 

Conclusion

We have successfully created an ASP.NET Core application using Angular 5 and Entity Framework core database first approach with the help of Visual Studio 2017 and SQL Server 2012. We have used Angular forms to get data from the user and also bind the dropdown list to database table using Entity framework.

You can also read my other articles here.
 
Please post your valuable feedbacks in the comments section below.