This tutorial will teach you how to make Crud Application using Asp.net Core Entity Framework with React Frontend application and Sqlserver Database using Api access Crudapplication.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; } } } |
Lets Connect with Front-End Application React
React
Installing React
1 | npx create-react-app aspcrud-frontend |
After complete the installation and run the project using following command.
1 | npm start run |
Now you see the React Welcome Page.
After that open the React project into VS code editor.
After that install the Bootstrap by typing the following command
1 | npm i bootstrap |
After that install the axios by typing the following command
1 | npm i axios |
Creating a new Component StudentCrud.js
StudentCrud.js
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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | import axios from "axios"; import { useEffect, useState } from "react"; function StudentCrud() { const [id, setId] = useState(""); const [stname, setName] = useState(""); const [course, setCourse] = useState(""); const [students, setUsers] = useState([]); useEffect(() => { (async () => await Load())(); }, []); async function Load() { const result = await axios.get("https://localhost:7195/api/Student/GetStudent"); setUsers(result.data); console.log(result.data); } async function save(event) { event.preventDefault(); try { await axios.post("https://localhost:7195/api/Student/AddStudent", { stname: stname, course: course, }); alert("Student Registation Successfully"); setId(""); setName(""); setCourse(""); Load(); } catch (err) { alert(err); } } async function editStudent(students) { setName(students.stname); setCourse(students.course); setId(students.id); } async function DeleteStudent(id) { await axios.delete("https://localhost:7195/api/Student/DeleteStudent/" + id); alert("Employee deleted Successfully"); setId(""); setName(""); setCourse(""); Load(); } async function update(event) { event.preventDefault(); try { await axios.patch("https://localhost:7195/api/Student/UpdateStudent/"+ students.find((u) => u.id === id).id || id, { id: id, stname: stname, course: course, } ); alert("Registation Updateddddd"); setId(""); setName(""); setCourse(""); Load(); } catch (err) { alert(err); } } return ( <div> <h1>Student Details</h1> <div class="container mt-4"> <form> <div class="form-group"> <input type="text" class="form-control" id="id" hidden value={id} onChange={(event) => { setId(event.target.value); }} /> <label>Student Name</label> <input type="text" class="form-control" id="stname" value={stname} onChange={(event) => { setName(event.target.value); }} /> </div> <div class="form-group"> <label>Course</label> <input type="text" class="form-control" id="course" value={course} onChange={(event) => { setCourse(event.target.value); }} /> </div> <div> <button class="btn btn-primary mt-4" onClick={save}> Register </button> <button class="btn btn-warning mt-4" onClick={update}> Update </button> </div> </form> </div> <br></br> <table class="table table-dark" align="center"> <thead> <tr> <th scope="col">Student Id</th> <th scope="col">Student Name</th> <th scope="col">Course</th> <th scope="col">Option</th> </tr> </thead> {students.map(function fn(student) { return ( <tbody> <tr> <th scope="row">{student.id} </th> <td>{student.stname}</td> <td>{student.course}</td> <td> <button type="button" class="btn btn-warning" onClick={() => editStudent(student)} > Edit </button> <button type="button" class="btn btn-danger" onClick={() => DeleteStudent(student.id)} > Delete </button> </td> </tr> </tbody> ); })} </table> </div> ); } export default StudentCrud; |
i have attached the video link below. which will do this tutorials step by step.