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
[Key] public int id { get; set; } public string stname { get; set; } public string course { get; set;
StudentDbContext
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"); } } }
Program.cs
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.
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
"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
PM>add-migration initial
then migration files has been created.
after that you have run the command as
update-database
now your database has been created you just open the sqlserver and check them database has created or not at the same time migration folder has been created in your project you can see that.
After that Select the Controller Folder Create the new Controller as Student Controller with Web Api
Student Controller
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;
}
}
}
After that you can check through the swagger.
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
npm install -g @angular/cli
After that create the new Project of Angular running by the following command
ng new frond-end
Select the SCSS Style for the Advanced CSS and Press Enter Key.
After complete the installation then run the project using following command.
ng serve
it will generate the url link to run the angular application.paste the url in to the browser
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
ng g c customer
After that install the Bootstrap by typing the following command
npm i bootstrap
After installed you have to set the path in to style.scss file
@import "~bootstrap/dist/css/bootstrap.css";
app.module.ts
FormModule
HttpClientModule
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
<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
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.