Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure

Introduction

 
In this article, we are creating a CRUD application using Angular 9 in the front end, Dot Net Core 3.1 in the backend, and Entity framework core and application deployed to Azure.
 
Prerequisites
  • Visual studio 2019
  • VS code
  • SQL Server
  • Azure Account
First, we are creating a database. Let's say the database name is EmployeeDb and we create one table for the store employee record. See the  below command for creating database and table.
 
Database Code
  1. CREATE DATABASE EmployeeDb  
  2. GO  
  3.   
  4. USE [EmployeeDb]  
  5. GO   
  6. SET ANSI_NULLS ON  
  7. GO  
  8.   
  9. SET QUOTED_IDENTIFIER ON  
  10. GO  
  11.   
  12. SET ANSI_PADDING ON  
  13. GO  
  14.   
  15. CREATE TABLE [dbo].[Employee](  
  16.     [EmpId] [int] IDENTITY(1,1) NOT NULL,  
  17.     [EmpName] [varchar](50) NOT NULL,  
  18.     [EmpContact] [varchar](50) NOT NULL,  
  19.     [EmpEmail] [varchar](50) NOT NULL,  
  20.     [EmpAddress] [varchar](250) NULL,  
  21. PRIMARY KEY CLUSTERED   
  22. (  
  23.     [EmpId] ASC  
  24. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  25. ON [PRIMARY]  
  26.   
  27. GO  
  28.   
  29. SET ANSI_PADDING ON  
  30. GO  
Now, we are creating a new dot net core web application. Open Visual Studio 2019 and select Asp.net core web application.
 

Server-Side Code

Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now enter our project name --  let's say the name is EmployeeServer. You can enter any name as you want. See the below screenshot for the project name and location of our application. 
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now select Asp.net core 3.1 and WebApi template then click on create button.
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
Our application is created successfully, now we are creating a new folder named Models and inside models, the folder creates a new class.
 
Employee.cs
  1. using System;   
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace EmployeeServer.Models  
  5. {  
  6.     public class Employee  
  7.     {  
  8.         [Key]  
  9.         public int? EmpId { getset; }  
  10.         public string EmpName { getset; }  
  11.         public string EmpContact { getset; }  
  12.         public string EmpEmail { getset; }  
  13.         public string EmpAddress { getset; }  
  14.     }  
  15. }  
Create a new folder Context for DB Context then create a new class with name as EmployeeContext. After creating the class we need to install packages for Entity framework core. 
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore
 Now we have installed a dependency for our application from manage NuGet packages. We are writing code as given below in the context class. 
 
EmployeeContext.cs 
  1. using EmployeeServer.Models;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4.    
  5.   
  6. namespace EmployeeServer.Context  
  7. {  
  8.     public class EmployeeContext : DbContext  
  9.     {  
  10.         public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)  
  11.         {  
  12.         }  
  13.         public DbSet<Employee> Employee { getset; }    
  14.          
  15.     }  
  16. }  
We are creating a new controller --  let's name it Employee controller and writing methods for performing create read update and delete operations.
 
EmployeeController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using EmployeeServer.Context;  
  6. using EmployeeServer.Models;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.AspNetCore.Mvc;  
  9.   
  10. namespace EmployeeServer.Controllers  
  11. {  
  12.     [Route("api/[controller]")]  
  13.     [ApiController]  
  14.     public class EmployeeController : ControllerBase  
  15.     {  
  16.         readonly EmployeeContext EmpDetails;  
  17.         public EmployeeController(EmployeeContext employeeContext)  
  18.         {  
  19.             EmpDetails = employeeContext;  
  20.         }  
  21.           
  22.         [HttpGet]  
  23.         public IEnumerable<Employee> Get()  
  24.         {  
  25.             var data = EmpDetails.Employee.ToList();  
  26.             return data;  
  27.         }   
  28.            
  29.         [HttpPost]  
  30.         public IActionResult Post([FromBody] Employee obj)  
  31.         {  
  32.             var data = EmpDetails.Employee.Add(obj);  
  33.             EmpDetails.SaveChanges();  
  34.             return Ok();  
  35.         }  
  36.           
  37.         [HttpPut("{id}")]  
  38.         public IActionResult Put(int id, [FromBody] Employee obj)  
  39.         {  
  40.             var data = EmpDetails.Employee.Update(obj);  
  41.             EmpDetails.SaveChanges();  
  42.             return Ok();  
  43.         }  
  44.   
  45.           
  46.         [HttpDelete("{id}")]  
  47.         public IActionResult Delete(int id)  
  48.         {  
  49.             var data = EmpDetails.Employee.Where(a => a.EmpId == id).FirstOrDefault();  
  50.             EmpDetails.Employee.Remove(data);  
  51.             EmpDetails.SaveChanges();  
  52.             return Ok();  
  53.   
  54.         }  
  55.     }  
  56. }  
  57.    
Now open the appsetting.json and write code for our database connection string.
 
appsettings.json 
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   "AllowedHosts""*",  
  10.   "ConnectionStrings": {  
  11.     "EmployeeDbConnection""server=LAPTOP-B4I8965\\SQLEXPRES;database=EmployeeDb;Trusted_Connection=true"  
  12.   }  
  13. }  
Open the startup class and write the code as given below. You also need to install dependencies for running our Angular static folder.
  •  Microsoft.AspNetCore.SpaServices.Extensions
Now we have installed Spa dependency for our application from manage NuGet packages. Create a new folder for front end files -- name it FrontEnd. After that run our application and confirm it is working fine.
 
Startup.cs
  1. using System;  
  2. using EmployeeServer.Context;  
  3. using Microsoft.AspNetCore.Builder;  
  4. using Microsoft.AspNetCore.Hosting;  
  5. using Microsoft.EntityFrameworkCore;  
  6. using Microsoft.Extensions.Configuration;  
  7. using Microsoft.Extensions.DependencyInjection;  
  8. using Microsoft.Extensions.Hosting;  
  9.   
  10.   
  11. namespace EmployeeServer  
  12. {  
  13.     public class Startup  
  14.     {  
  15.         public Startup(IConfiguration configuration)  
  16.         {  
  17.             Configuration = configuration;  
  18.         }  
  19.   
  20.         public IConfiguration Configuration { get; }  
  21.   
  22.         public void ConfigureServices(IServiceCollection services)  
  23.         {  
  24.             services.AddControllers();  
  25.             services.AddDbContextPool<EmployeeContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDbConnection")));  
  26.             services.AddSpaStaticFiles(configuration =>{  
  27.                 configuration.RootPath = "FrontEnd/dist";  
  28.             });  
  29.               
  30.         }  
  31.   
  32.         
  33.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  34.         {  
  35.             if (env.IsDevelopment())  
  36.             {  
  37.                 app.UseDeveloperExceptionPage();  
  38.             }  
  39.             app.UseCors(builder => builder  
  40.               .AllowAnyHeader()  
  41.               .AllowAnyMethod()  
  42.               .SetIsOriginAllowed((host) => true)  
  43.               .AllowCredentials()  
  44.               );  
  45.             app.UseHttpsRedirection();             
  46.             app.UseRouting();  
  47.             app.UseAuthorization();  
  48.   
  49.             app.UseEndpoints(endpoints =>  
  50.             {  
  51.                 endpoints.MapControllers();  
  52.             });  
  53.   
  54.             app.UseSpaStaticFiles();  
  55.             app.UseSpa(spa =>  
  56.             {  
  57.                 spa.Options.SourcePath = "FrontEnd";                  
  58.             }); 
  59.   
  60.         }  
  61.     }  
  62. }  

Front-End Code

 
Now we are creating a new Angular application using the  below command. Let's say the  application name is EmployeeFrontEnd as we mentioned above.
  • ng new EmployeeFrontEnd
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure

 
Once our Angular project is created successfully, open project in vs code. Create one service for HTTP service using the below command:
  • ng g s service
After creating service write the below code.
 
service.service.ts 
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient,HttpHeaders }    from '@angular/common/http';  
  3. @Injectable({  
  4.   providedIn: 'root'  
  5. })  
  6.   
  7. export class ServiceService {  
  8.   
  9. constructor(private http: HttpClient) { }  
  10.   httpOptions = {  
  11.     headers: new HttpHeaders({  
  12.       'Content-Type''application/json'  
  13.     })  
  14.   }    
  15.   getData(){  
  16.        
  17.     return this.http.get('/api/Employee');  //https://localhost:44352/ webapi host url  
  18.   }  
  19.   
  20.   postData(formData){  
  21.     return this.http.post('/api/Employee',formData);  
  22.   }  
  23.   
  24.   putData(id,formData){  
  25.     return this.http.put('/api/Employee/'+id,formData);  
  26.   }  
  27.   deleteData(id){  
  28.     return this.http.delete('/api/Employee/'+id);  
  29.   }  
  30.     
  31. }  
Open app.module file and import some package for form builder and import service and install bootstrap using this command npm install bootstrap.
 
app.module.ts 
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  6. import { HttpClientModule }    from '@angular/common/http';  
  7. import {ServiceService} from './service.service';  
  8. @NgModule({  
  9.   declarations: [  
  10.     AppComponent  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule,  
  14.     FormsModule,  
  15.     ReactiveFormsModule,  
  16.     HttpClientModule  
  17.   
  18.   ],  
  19.   providers: [ServiceService],  
  20.   bootstrap: [AppComponent]  
  21. })  
  22. export class AppModule { }  
Open app.component ts file and writethe  below code for the call methods of service.
 
app.component.ts 
  1. import { Component } from '@angular/core';  
  2. import {ServiceService} from './service.service';  
  3. import { FormGroup, FormControl,Validators } from '@angular/forms';   
  4. @Component({  
  5.   selector: 'app-root',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent {  
  10.   title = 'EmployeeFrontEnd';  
  11.      
  12.   constructor(private ServiceService: ServiceService) { }  
  13.   data: any;  
  14.   EmpForm: FormGroup;  
  15.   submitted = false;   
  16.   EventValue: any = "Save";  
  17.   
  18.   ngOnInit(): void {  
  19.     this.getdata();  
  20.   
  21.     this.EmpForm = new FormGroup({  
  22.       empId: new FormControl(null),  
  23.       empName: new FormControl("",[Validators.required]),        
  24.       empContact: new FormControl("",[Validators.required]),  
  25.       empEmail:new FormControl("",[Validators.required]),  
  26.       empAddress: new FormControl("",[Validators.required]),  
  27.     })    
  28.   }  
  29.   getdata() {  
  30.     this.ServiceService.getData().subscribe((data: any[]) => {  
  31.       this.data = data;  
  32.     })  
  33.   }  
  34.   deleteData(id) {  
  35.     this.ServiceService.deleteData(id).subscribe((data: any[]) => {  
  36.       this.data = data;  
  37.       this.getdata();  
  38.     })  
  39.   }  
  40.   Save() {   
  41.     this.submitted = true;  
  42.     
  43.      if (this.EmpForm.invalid) {  
  44.             return;  
  45.      }  
  46.     this.ServiceService.postData(this.EmpForm.value).subscribe((data: any[]) => {  
  47.       this.data = data;  
  48.       this.resetFrom();  
  49.   
  50.     })  
  51.   }  
  52.   Update() {   
  53.     this.submitted = true;  
  54.     
  55.     if (this.EmpForm.invalid) {  
  56.      return;  
  57.     }        
  58.     this.ServiceService.putData(this.EmpForm.value.empId,this.EmpForm.value).subscribe((data: any[]) => {  
  59.       this.data = data;  
  60.       this.resetFrom();  
  61.     })  
  62.   }  
  63.   
  64.   EditData(Data) {  
  65.     this.EmpForm.controls["empId"].setValue(Data.empId);  
  66.     this.EmpForm.controls["empName"].setValue(Data.empName);      
  67.     this.EmpForm.controls["empContact"].setValue(Data.empContact);  
  68.     this.EmpForm.controls["empEmail"].setValue(Data.empEmail);  
  69.     this.EmpForm.controls["empAddress"].setValue(Data.empAddress);  
  70.     this.EventValue = "Update";  
  71.   }  
  72.   
  73.   resetFrom()  
  74.   {     
  75.     this.getdata();  
  76.     this.EmpForm.reset();  
  77.     this.EventValue = "Save";  
  78.     this.submitted = false;   
  79.   }  
  80. }  
Open app.component Html file and write the below code.
 
app.component.html 
  1. <div class="container">  
  2.     
  3. <form [formGroup]="EmpForm" (ngSubmit)="this[EventValue]()">  
  4.     
  5.     <h3>Employee Table CRUD Operation</h3>  
  6.     <div class="row">  
  7.          
  8.     <table class="table">  
  9.     <tr>  
  10.       <td>Name</td>  
  11.       <td>  
  12.         <input type="hidden" formControlName="empId">  
  13.         <input type="text" formControlName="empName">  
  14.         <div *ngIf="submitted && EmpForm.controls.empName.errors" class="text-danger">  
  15.           <div *ngIf="EmpForm.controls.empName.errors.required">Name is required</div>  
  16.         </div>   
  17.       </td>  
  18.     </tr>  
  19.       
  20.     <tr>  
  21.       <td>Contact</td>  
  22.       <td><input type="text" formControlName="empContact">  
  23.         <div *ngIf="submitted && EmpForm.controls.empContact.errors" class="text-danger">  
  24.           <div *ngIf="EmpForm.controls.empContact.errors.required">Contact is required</div>  
  25.         </div>   
  26.       </td>  
  27.     </tr>  
  28.     <tr>  
  29.       <td>Email</td>  
  30.       <td>  
  31.         <input type="text" formControlName="empEmail">  
  32.         <div *ngIf="submitted && EmpForm.controls.empEmail.errors" class="text-danger">  
  33.           <div *ngIf="EmpForm.controls.empEmail.errors.required">Email is required</div>  
  34.         </div>  
  35.       </td>  
  36.     </tr>  
  37.     <tr>  
  38.       <td>Address</td>  
  39.       <td>  
  40.         <input type="text" formControlName="empAddress">  
  41.         <div *ngIf="submitted && EmpForm.controls.empAddress.errors" class="text-danger">  
  42.           <div *ngIf="EmpForm.controls.empAddress.errors.required">Address is required</div>  
  43.         </div>  
  44.           
  45.       </td>  
  46.     </tr>  
  47.     <tr>  
  48.   
  49.       <td colspan="2">  
  50.         <button type="submit" class="btn btn-primary">{{EventValue}}</button>  
  51.       </td>  
  52.     </tr>  
  53.       
  54.   </table>  
  55.   </div>  
  56.      
  57.  <div class="row">  
  58.   <table class="table table-striped">  
  59.     <tr>  
  60.       <td>Id</td>  
  61.       <td>Name</td>  
  62.         
  63.       <td>Contact</td>  
  64.       <td>Email</td>  
  65.       <td>Address</td>  
  66.       <td>Edit</td>  
  67.       <td>Delete</td>  
  68.     </tr>  
  69.   
  70.     <tr *ngFor="let d of data">  
  71.       <td>{{d.empId}}</td>  
  72.       <td>{{d.empName}}</td>  
  73.        
  74.       <td>{{d.empContact}}</td>  
  75.       <td>{{d.empEmail}}</td>  
  76.       <td>{{d.empAddress}}</td>  
  77.       <td><a (click)="EditData(d)" class="btn btn-warning">Edit</a></td>  
  78.       <td><a (click)="deleteData(d.empId)" class="btn btn-danger">Delete</a></td>    
  79.     </tr>  
  80.   </table>  
  81. </div>  
  82. </form>  
  83.   
  84. </div>  
 Now run our front end application and confirm it is working fine using ng serve command and ng build command for creating dist folder.
  • ng serve
  • ng build --prod 
After creating dist folder we need to copy and paste the dist folder to our server-side FrontEnd folder and now run web API application. We can see the below output.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure

Azure Portal

 
Now we need to log in to the Azure portal to create app service and SQL server. After successfully  logging in to your Azure account find app service and create new service as in the  below screenshot.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Click on create app service or add button and fill in some basic details for app service like resource group name and name of our application runtime stack, region etc. Now click on review and create button. 
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now click on create app service button. After your deployment is complete we are getting this message given below.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now we need to create SQL server. Go to the Azure home page and search for SQL Server then click on create SQL server.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
Now we have to fill in some details for creating SQL database server like resource group, server name, location and administrator login details. Then click on review and create button.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
After validating details click on create button. When our server is deployed successfully, we will get the  below screen. Click on the go-to resource button.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
Now create a new database by clicking on the button. Create a database as we can seebelow.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
After clicking on create database and giving the giving the database the same name as our local one and validating details,  click on the create button.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now our database is created and now click on show database connection string. 
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now click on firewalls  allow Azure service and resourcesto access server and client IP address.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now open our local SQL server and connection server name as given in the connection string and log in with username and password. After successfully logging in create a table by using the above command we were given for Employee Table;  or copy from a local database and  run the script to this server.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now we need to copy the connection string of Azure database, paste to our appsetting JSON file and do some code changes for startup cs file for using the static angular file.
  1. // add connection string in appsetting.json file

  2. "EmployeeDbConnection""Server=tcp:mysql-lserver.database.windows.net,1433;Initial Catalog=EmployeeDb;Persist Security Info=False;User ID={yourpassword};Password={yourpassword};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"  
  1. // add this code startup.cs file  
  2.   
  3. FileServerOptions defaultFileOptions = new FileServerOptions();  
  4.             defaultFileOptions.DefaultFilesOptions.DefaultFileNames.Clear();  
  5.             defaultFileOptions.DefaultFilesOptions.DefaultFileNames.Add("index.html");  
  6.             app.UseFileServer(defaultFileOptions);  
  7.             app.UseStaticFiles(new StaticFileOptions()  
  8.             {  
  9.                 FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "FrontEnd/dist")),  
  10.                  
  11.             });  
After that click on publish button on App service. We already have an app service name as Employeeapplication so click on select existing and click on create a profile.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now we can see the resource group, and select application as EmployeeApplication and click on the ok button.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now click on the Publish button. When the application is published successfully, open Site Url and see the output. 
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 
Now we can see our application has been deployed to the Azure portal. We can check that the application is performing CRUD operations.
 
Build Crud Operation Using Angular 9 And .Net Core 3.1 WebAPI And Deploy To Azure
 

Summary

 
In this article, we learned how to create CRUD application using Angular 9 in the front end, Dot Net Core 3.1 in the backend, and Entity framework core and application deployed to Azure. I hope you enjoyed this article. If you have any query related to this code, please comment in the comments section.

Recommended Ebook

Dockerizing ASP.NET Core and Blazor Applications on Mac

Download Now!
Similar Articles