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
- CREATE DATABASE EmployeeDb
- GO
-
- USE [EmployeeDb]
- GO
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[Employee](
- [EmpId] [int] IDENTITY(1,1) NOT NULL,
- [EmpName] [varchar](50) NOT NULL,
- [EmpContact] [varchar](50) NOT NULL,
- [EmpEmail] [varchar](50) NOT NULL,
- [EmpAddress] [varchar](250) NULL,
- PRIMARY KEY CLUSTERED
- (
- [EmpId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- SET ANSI_PADDING ON
- 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
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.
Now select Asp.net core 3.1 and WebApi template then click on create button.
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
- using System;
- using System.ComponentModel.DataAnnotations;
-
- namespace EmployeeServer.Models
- {
- public class Employee
- {
- [Key]
- public int? EmpId { get; set; }
- public string EmpName { get; set; }
- public string EmpContact { get; set; }
- public string EmpEmail { get; set; }
- public string EmpAddress { get; set; }
- }
- }
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
- using EmployeeServer.Models;
- using Microsoft.EntityFrameworkCore;
- using System;
-
-
- namespace EmployeeServer.Context
- {
- public class EmployeeContext : DbContext
- {
- public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)
- {
- }
- public DbSet<Employee> Employee { get; set; }
-
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using EmployeeServer.Context;
- using EmployeeServer.Models;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
-
- namespace EmployeeServer.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- public class EmployeeController : ControllerBase
- {
- readonly EmployeeContext EmpDetails;
- public EmployeeController(EmployeeContext employeeContext)
- {
- EmpDetails = employeeContext;
- }
-
- [HttpGet]
- public IEnumerable<Employee> Get()
- {
- var data = EmpDetails.Employee.ToList();
- return data;
- }
-
- [HttpPost]
- public IActionResult Post([FromBody] Employee obj)
- {
- var data = EmpDetails.Employee.Add(obj);
- EmpDetails.SaveChanges();
- return Ok();
- }
-
- [HttpPut("{id}")]
- public IActionResult Put(int id, [FromBody] Employee obj)
- {
- var data = EmpDetails.Employee.Update(obj);
- EmpDetails.SaveChanges();
- return Ok();
- }
-
-
- [HttpDelete("{id}")]
- public IActionResult Delete(int id)
- {
- var data = EmpDetails.Employee.Where(a => a.EmpId == id).FirstOrDefault();
- EmpDetails.Employee.Remove(data);
- EmpDetails.SaveChanges();
- return Ok();
-
- }
- }
- }
-
Now open the appsetting.json and write code for our database connection string.
appsettings.json
- {
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*",
- "ConnectionStrings": {
- "EmployeeDbConnection": "server=LAPTOP-B4I8965\\SQLEXPRES;database=EmployeeDb;Trusted_Connection=true"
- }
- }
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
- using System;
- using EmployeeServer.Context;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
-
-
- namespace EmployeeServer
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers();
- services.AddDbContextPool<EmployeeContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDbConnection")));
- services.AddSpaStaticFiles(configuration =>{
- configuration.RootPath = "FrontEnd/dist";
- });
-
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- app.UseCors(builder => builder
- .AllowAnyHeader()
- .AllowAnyMethod()
- .SetIsOriginAllowed((host) => true)
- .AllowCredentials()
- );
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseAuthorization();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
-
- app.UseSpaStaticFiles();
- app.UseSpa(spa =>
- {
- spa.Options.SourcePath = "FrontEnd";
- });
-
- }
- }
- }
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.
Once our Angular project is created successfully, open project in vs code. Create one service for HTTP service using the below command:
After creating service write the below code.
service.service.ts
- import { Injectable } from '@angular/core';
- import { HttpClient,HttpHeaders } from '@angular/common/http';
- @Injectable({
- providedIn: 'root'
- })
-
- export class ServiceService {
-
- constructor(private http: HttpClient) { }
- httpOptions = {
- headers: new HttpHeaders({
- 'Content-Type': 'application/json'
- })
- }
- getData(){
-
- return this.http.get('/api/Employee');
- }
-
- postData(formData){
- return this.http.post('/api/Employee',formData);
- }
-
- putData(id,formData){
- return this.http.put('/api/Employee/'+id,formData);
- }
- deleteData(id){
- return this.http.delete('/api/Employee/'+id);
- }
-
- }
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
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppComponent } from './app.component';
- import { FormsModule, ReactiveFormsModule } from '@angular/forms';
- import { HttpClientModule } from '@angular/common/http';
- import {ServiceService} from './service.service';
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule,
- FormsModule,
- ReactiveFormsModule,
- HttpClientModule
-
- ],
- providers: [ServiceService],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Open app.component ts file and writethe below code for the call methods of service.
app.component.ts
- import { Component } from '@angular/core';
- import {ServiceService} from './service.service';
- import { FormGroup, FormControl,Validators } from '@angular/forms';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title = 'EmployeeFrontEnd';
-
- constructor(private ServiceService: ServiceService) { }
- data: any;
- EmpForm: FormGroup;
- submitted = false;
- EventValue: any = "Save";
-
- ngOnInit(): void {
- this.getdata();
-
- this.EmpForm = new FormGroup({
- empId: new FormControl(null),
- empName: new FormControl("",[Validators.required]),
- empContact: new FormControl("",[Validators.required]),
- empEmail:new FormControl("",[Validators.required]),
- empAddress: new FormControl("",[Validators.required]),
- })
- }
- getdata() {
- this.ServiceService.getData().subscribe((data: any[]) => {
- this.data = data;
- })
- }
- deleteData(id) {
- this.ServiceService.deleteData(id).subscribe((data: any[]) => {
- this.data = data;
- this.getdata();
- })
- }
- Save() {
- this.submitted = true;
-
- if (this.EmpForm.invalid) {
- return;
- }
- this.ServiceService.postData(this.EmpForm.value).subscribe((data: any[]) => {
- this.data = data;
- this.resetFrom();
-
- })
- }
- Update() {
- this.submitted = true;
-
- if (this.EmpForm.invalid) {
- return;
- }
- this.ServiceService.putData(this.EmpForm.value.empId,this.EmpForm.value).subscribe((data: any[]) => {
- this.data = data;
- this.resetFrom();
- })
- }
-
- EditData(Data) {
- this.EmpForm.controls["empId"].setValue(Data.empId);
- this.EmpForm.controls["empName"].setValue(Data.empName);
- this.EmpForm.controls["empContact"].setValue(Data.empContact);
- this.EmpForm.controls["empEmail"].setValue(Data.empEmail);
- this.EmpForm.controls["empAddress"].setValue(Data.empAddress);
- this.EventValue = "Update";
- }
-
- resetFrom()
- {
- this.getdata();
- this.EmpForm.reset();
- this.EventValue = "Save";
- this.submitted = false;
- }
- }
Open app.component Html file and write the below code.
app.component.html
- <div class="container">
-
- <form [formGroup]="EmpForm" (ngSubmit)="this[EventValue]()">
-
- <h3>Employee Table CRUD Operation</h3>
- <div class="row">
-
- <table class="table">
- <tr>
- <td>Name</td>
- <td>
- <input type="hidden" formControlName="empId">
- <input type="text" formControlName="empName">
- <div *ngIf="submitted && EmpForm.controls.empName.errors" class="text-danger">
- <div *ngIf="EmpForm.controls.empName.errors.required">Name is required</div>
- </div>
- </td>
- </tr>
-
- <tr>
- <td>Contact</td>
- <td><input type="text" formControlName="empContact">
- <div *ngIf="submitted && EmpForm.controls.empContact.errors" class="text-danger">
- <div *ngIf="EmpForm.controls.empContact.errors.required">Contact is required</div>
- </div>
- </td>
- </tr>
- <tr>
- <td>Email</td>
- <td>
- <input type="text" formControlName="empEmail">
- <div *ngIf="submitted && EmpForm.controls.empEmail.errors" class="text-danger">
- <div *ngIf="EmpForm.controls.empEmail.errors.required">Email is required</div>
- </div>
- </td>
- </tr>
- <tr>
- <td>Address</td>
- <td>
- <input type="text" formControlName="empAddress">
- <div *ngIf="submitted && EmpForm.controls.empAddress.errors" class="text-danger">
- <div *ngIf="EmpForm.controls.empAddress.errors.required">Address is required</div>
- </div>
-
- </td>
- </tr>
- <tr>
-
- <td colspan="2">
- <button type="submit" class="btn btn-primary">{{EventValue}}</button>
- </td>
- </tr>
-
- </table>
- </div>
-
- <div class="row">
- <table class="table table-striped">
- <tr>
- <td>Id</td>
- <td>Name</td>
-
- <td>Contact</td>
- <td>Email</td>
- <td>Address</td>
- <td>Edit</td>
- <td>Delete</td>
- </tr>
-
- <tr *ngFor="let d of data">
- <td>{{d.empId}}</td>
- <td>{{d.empName}}</td>
-
- <td>{{d.empContact}}</td>
- <td>{{d.empEmail}}</td>
- <td>{{d.empAddress}}</td>
- <td><a (click)="EditData(d)" class="btn btn-warning">Edit</a></td>
- <td><a (click)="deleteData(d.empId)" class="btn btn-danger">Delete</a></td>
- </tr>
- </table>
- </div>
- </form>
-
- </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.
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.
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.
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.
Now click on create app service button. After your deployment is complete we are getting this message given below.
Now we need to create SQL server. Go to the Azure home page and search for SQL Server then click on create SQL server.
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.
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.
Now create a new database by clicking on the button. Create a database as we can seebelow.
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.
Now our database is created and now click on show database connection string.
Now click on firewalls allow Azure service and resourcesto access server and client IP address.
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.
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.
- // add connection string in appsetting.json file
- "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;"
-
-
- FileServerOptions defaultFileOptions = new FileServerOptions();
- defaultFileOptions.DefaultFilesOptions.DefaultFileNames.Clear();
- defaultFileOptions.DefaultFilesOptions.DefaultFileNames.Add("index.html");
- app.UseFileServer(defaultFileOptions);
- app.UseStaticFiles(new StaticFileOptions()
- {
- FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "FrontEnd/dist")),
-
- });
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.
Now we can see the resource group, and select application as EmployeeApplication and click on the ok button.
Now click on the Publish button. When the application is published successfully, open Site Url and see the output.
Now we can see our application has been deployed to the Azure portal. We can check that the application is performing CRUD operations.
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.