CRUD Operation in Asp.Net Core Web API
Here in this post I have shared the source code of CRUD operation in ASP.NET Core Web Api. Also i have shared video tutoriol of crud operation in Asp.Net Core Web Api.
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDb;Database=BasicCrud;Trusted_Connection=true"
}
}
Data/ApplicationDbContext.cs
using BasicCrud.Models;
using Microsoft.EntityFrameworkCore;
namespace BasicCrud.Data
{
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
public DbSet<Student>? Students { get; set; }
}
}
Models/Student.cs
using System.ComponentModel.DataAnnotations;
namespace BasicCrud.Models
{
public class Student
{
public int Id { get; set; }
[Required]
public string? StudentName { get; set; }
public string? Address { get; set; }
public string? Standard { get; set; }
}
}
program.cs
using BasicCrud.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options=>options.UseSqlServer(connectionString));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Controllers/StudentsController.cs
using BasicCrud.Data;
using BasicCrud.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BasicCrud.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public StudentsController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetAllStudents()
{
var students = await _context.Students.ToListAsync();
return Ok(students);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetStudentById(int id)
{
var student = await _context.Students.FirstOrDefaultAsync(x => x.Id == id);
if(student == null)
{
return NotFound();
}
return Ok(student);
}
[HttpPost]
public async Task<IActionResult> AddStudent([FromBody] Student student)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
await _context.Students.AddAsync(student);
await _context.SaveChangesAsync();
return Ok();
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateStudent(int id, [FromBody] Student student)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var existingStudent = await _context.Students.FirstOrDefaultAsync(x => x.Id == id);
if (existingStudent == null)
{
return NotFound();
}
existingStudent.StudentName = student.StudentName;
existingStudent.Address = student.Address;
existingStudent.Standard = student.Standard;
await _context.SaveChangesAsync();
return Ok();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteStudent(int id)
{
var student = await _context.Students.FirstOrDefaultAsync(x => x.Id == id);
if (student == null)
{
return NotFound();
}
_context.Students.Remove(student);
_context.SaveChangesAsync();
return Ok();
}
}
}