This tutorial will teach you how to make Crud Application using Asp.net Core Entity Framework with Angular Frontend application and Sql Server Database using Api access Crud application.this tutorial explains the Code First approach.
Install the required Dependencies
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Newtonsoft.Json
First Step Select the Model Folder Right Click and Create the Class Student.cs
Student.cs
1 2 3 4 | [Key] public int id { get; set; } public string stname { get; set; } public string course { get; set; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | using Microsoft.EntityFrameworkCore; namespace ReactAspCrud.Models { public class StudentDbContext : DbContext { public StudentDbContext(DbContextOptions<StudentDbContext> options) : base(options) { } public DbSet<Student> Student { get;set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source=.; Initial Catalog=lbs; User Id=sa; password=123; TrustServerCertificate= True"); } } } |
Add these Context inside the Program.cs file
Establish the Database Connection
builder.Services.AddDbContext<StudentDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString(“StudentDbContext”)));
Connect the WebApi for Allow the Permissions
app.UseCors(policy => policy.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
I attached the full code of Program.cs file where you going paste the above code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using Microsoft.EntityFrameworkCore; using ReactAspCrud.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext<StudentDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext"))); var app = builder.Build(); app.UseCors(policy => policy.AllowAnyHeader() .AllowAnyMethod() .SetIsOriginAllowed(origin => true) .AllowCredentials()); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); |
appsettings.json
Paste the ConnectionStrings
1 2 3 4 | "AllowedHosts": "*", "ConnectionStrings": { "StudentDbContext": "Server=.;Database=lbs;Trusted_Connection=True;MultipleActiveResultSets=true" } |
After that Go to Tools->NuGet Package Manager->Package Manager Console
then you can get the console . you have add-migration initial
1 | PM>add-migration initial |
then migration files has been created.
after that you have run the command as
1 | update-database |
After that Select the Controller Folder Create the new Controller as Student Controller with Web Api
Student Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using ReactAspCrud.Models; namespace ReactAspCrud.Controllers { [Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { private readonly StudentDbContext _studentDbContext; public StudentController(StudentDbContext studentDbContext) { _studentDbContext = studentDbContext; } [HttpGet] [Route("GetStudent")] public async Task<IEnumerable<Student>> GetStudents() { return await _studentDbContext.Student.ToListAsync(); } [HttpPost] [Route("AddStudent")] public async Task<Student> AddStudent(Student objStudent) { _studentDbContext.Student.Add(objStudent); await _studentDbContext.SaveChangesAsync(); return objStudent; } [HttpPatch] [Route("UpdateStudent/{id}")] public async Task<Student> UpdateStudent(Student objStudent) { _studentDbContext.Entry(objStudent).State= EntityState.Modified; await _studentDbContext.SaveChangesAsync(); return objStudent; } [HttpDelete] [Route("DeleteStudent/{id}")] public bool DeleteStudent(int id) { bool a = false; var student = _studentDbContext.Student.Find(id); if (student != null) { a = true; _studentDbContext.Entry(student).State= EntityState.Deleted; _studentDbContext.SaveChanges(); } else { a = false; } return a; } } } |
Angular
Angular is a front-end application we have already created the folder front end inside the folder open the command prompt and type the commands.
Installing Angular CLI
1 | npm install -g @angular/cli |
After that create the new Project of Angular running by the following command
1 | ng new frond-end |
After complete the installation then run the project using following command.
1 | ng serve |
Now you see the Angular Welcome Page.
After that open the Angular project into VS code editor.
now you can see the following file structure
Creating a new Component Student Crud
1 | ng g c customer |
1 | npm i bootstrap |
1 | @import "~bootstrap/dist/css/bootstrap.css"; |
FormModule
HttpClientModule
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CustomerComponent } from './customer/customer.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, CustomerComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
add these module into the app.module.ts file then only we will manage the forms and Http requests
studentcrud.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <div class="container mt-4" > <div class="card"> <h1>Student Registation</h1> <form> <div class="form-group"> <label>Student Name</label> <input type="text" [(ngModel)]="stname" [ngModelOptions]="{standalone: true}" class="form-control" id="stname" placeholder="Enter Name"> </div> <div class="form-group"> <label>Course</label> <input type="text" [(ngModel)]="course" [ngModelOptions]="{standalone: true}" class="form-control" id="course" placeholder="Enter Name"> </div> <button type="submit" class="btn btn-primary mt-4" (click)="save()" >Save</button> </form> </div> <div class="container mt-4" > <h1>Student Table</h1> <table class="table"> <thead> <h1 *ngIf="!isResultLoaded">Loading.................</h1> <tr> <th scope="col">ID</th> <th scope="col">Student Name</th> <th scope="col">Course</th> </tr> </thead> <tbody> <tr *ngFor="let StudentItem of StudentArray"> <td>{{StudentItem.id }}</td> <td>{{StudentItem.stname }}</td> <td>{{StudentItem.course }}</td> <td> <button type="button" class="btn btn-success" (click)="setUpdate(StudentItem)">Edit</button> <button type="button" class="btn btn-danger" (click)="setDelete(StudentItem)">Delete</button> </td> </tr> </tbody> </table> </div> |
studentcrud.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-studentcrud', templateUrl: './studentcrud.component.html', styleUrls: ['./studentcrud.component.scss'] }) export class StudentcrudComponent { StudentArray : any[] = []; isResultLoaded = false; isUpdateFormActive = false; stname: string =""; course: string =""; currentStudentID = ""; constructor(private http: HttpClient ) { this.getAllStudent(); } ngOnInit(): void { } getAllStudent() { this.http.get("https://localhost:7195/api/Student/GetStudent") .subscribe((resultData: any)=> { this.isResultLoaded = true; console.log(resultData); this.StudentArray = resultData; }); } register() { // this.isLogin = false; // alert("hi"); let bodyData = { "stname" : this.stname, "course" : this.course, }; this.http.post("https://localhost:7195/api/Student/AddStudent",bodyData).subscribe((resultData: any)=> { console.log(resultData); alert("Student Registered Successfully") this.getAllStudent(); // this.name = ''; // this.address = ''; // this.mobile = 0; }); } setUpdate(data: any) { this.stname = data.stname; this.course = data.course; this.currentStudentID = data.id; } UpdateRecords() { let bodyData = { "stname" : this.stname, "course" : this.course, }; this.http.patch("https://localhost:7195/api/Student/UpdateStudent"+ "/"+ this.currentStudentID,bodyData).subscribe((resultData: any)=> { console.log(resultData); alert("Student Registered Updateddd") this.getAllStudent(); }); } save() { if(this.currentStudentID == '') { this.register(); } else { this.UpdateRecords(); } } setDelete(data: any) { this.http.delete("https://localhost:7195/api/Student/DeleteStudent"+ "/"+ data.id).subscribe((resultData: any)=> { console.log(resultData); alert("Student Deletedddd") this.getAllStudent(); }); } } |
i have attached the video link below. which will do this tutorials step by step.