Build Crud Operation Using Angular 9
formGroup And .Net Core 3.1 Code
First Web API
Introduction
In this article, we are creating a CRUD Operation using Angular 9 in the front end and Dot Net Core 3.1 in the backend, and Entity framework core Using CodeFirst approach let's start.
Prerequisites :-
- Visual studio 2019 Or Any
- VS code
- SQL Server
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 select Asp.net core Web API template then click on Next button.
Now enter our project name - let's say the name is Employee. You can enter any name as you want. See the below screenshot for the project name and location of our application.
After that Click on Create Button.
Our application is created successfully, Our structure Look Like This-
EmployeeInfo.cs
public class EmployeeInfo
{
[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 dependency for our application from manage NuGet packages. We are writing code as given below in the context class. Ex Data Layer.
EmployeeContext.cs
public class EmployeeContext:DbContext
{
public EmployeeContext(DbContextOptions<EmployeeContext>opt):base(opt)
{
}
public DbSet<EmployeeInfo> employees { get; set; }
}
Now open the appsetting.json and write code for our database connection string.
appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"EmployeeDbConnection": "Data Source=;Initial Catalog=UserManagement;Integrated Security=True"
}
},
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 EmployeeServer.Dal;
using EmployeeServer.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmployeeServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
readonly EmployeeContext EmpDetails;
public EmployeeController(EmployeeContext employeeContext)
{
EmpDetails = employeeContext;
}
// Our Get Method ../////
[HttpGet]
public IEnumerable<Employee> Get()
{
var data = EmpDetails.Employee.ToList();
return data;
}
// Our Post Method ../////
[HttpPost]
public IActionResult Post([FromBody] Employee obj)
{
var data = EmpDetails.Employee.Add(obj);
EmpDetails.SaveChanges();
return Ok();
}
// Our Update Method ../////
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Employee obj)
{
var data = EmpDetails.Employee.Update(obj);
EmpDetails.SaveChanges();
return Ok();
}
// Our Delete Method ../////
[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();
}
}
}
Screenshot Look Like This->
Open the startup class and write the code as given below Here We Are Set database Connection on Run time.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContextPool<EmployeeContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDbConnection")));
}
Screenshot look like this.
We have created entity models and DbContext object above so it is now time to generate our database with the help of migrations. Migrations allow us to easily create a new database and then incrementally update the database schema to keep it in sync with the application models. You can run migrations using .NET Core CLI tools which will work on all platforms but if you want to stay within Visual Studio then you can also use Package Manager Console tools. For this tutorial, I will use Package Manager Console tools so let open Package Manager Console and add our first migration using the following Add-Migration command.
1 | Add-Migration InitialDatabaseCreate |
EF Core will create a directory called Migrations in the project and will also generate some files in this folder. Every time you will add a new migration using the Add-Migration command, a new file will be created in the Migrations folder.
We are now ready to create our database and tables using the migration code generated for us. This can be done by running Update-Database command in Package Manager Console within Visual Studio.
1 | Update-Database |
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 EmployeeServer.Dal;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmployeeServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContextPool<EmployeeContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDbConnection")));
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "FrontEnd/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
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.
- ng new EmployeeFrontEnd
Now ng serve --o
Run The Project It's look like-
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
- 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'); //https://localhost:44352/ webapi host url
- }
- 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=> {
this.data = data;
})
}
deleteData(id:any) {
this.ServiceService.deleteData(id).subscribe(data => {
this.data = data;
this.getdata();
})
}
Save() {
this.submitted = true;
if (this.EmpForm.invalid) {
return;
}
this.ServiceService.postData(this.EmpForm.value).subscribe(data => {
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=> {
this.data = data;
this.resetFrom();
})
}
EditData(Data:any) {
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.
- <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.
- ng serve
- ng build --prod














0 Comments