Simple CRUD Operation Web API
Model
---------------------------------------------------------
namespace ProjectWebApi.Model
{
public class Brand
{
public int? Id { get; set; }
public string? BrandName { get; set; }
}
}
-------------------------
DbContext.cs
----------
using Microsoft.EntityFrameworkCore;
namespace ProjectWebApi.Model
{
public class BrandDbContext:DbContext
{
public BrandDbContext()
{
}
public BrandDbContext(DbContextOptions<BrandDbContext> options):base(options) {
}
public DbSet<Brand> Brands { get;set; }
internal void FindAsync(Brand brand)
{
throw new NotImplementedException();
}
}
}
-----------------------------------------------
appsetting.json
------------------------
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"BrandCS": "server= enter ;database=brandDB;Integrated Security=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
},
"AllowedHosts": "*"
}
-------------------------------------------
Package Manager
--------------------------
Add-Migration initiated
then
update-database
------------------------------
Controller
------------------------
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Any;
using ProjectWebApi.Model;
namespace ProjectWebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BrandController : ControllerBase
{
private BrandDbContext _dbContext;
public BrandController(BrandDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Brand>>> GetBrand()
{
if (_dbContext.Brands == null)
{
return NotFound();
}
return await _dbContext.Brands.ToListAsync();
}
[HttpGet("GetBrandWithParameter")]
public async Task<ActionResult<Brand>> GetBrand(int Id)
{
if (_dbContext.Brands == null)
{
return NotFound();
}
var brand = await _dbContext.Brands.FindAsync(Id);
if (brand == null)
{
return NotFound();
}
return brand;
}
[HttpPost]
public async Task<ActionResult<Brand>> BrandInsert(Brand brand)
{
_dbContext.Brands.Add(brand);
await _dbContext.SaveChangesAsync();
return Ok("done");
}
[HttpPut("Update")]
public async Task<IActionResult> BrandUpdate(int id, Brand brand)
{
if (id != brand.Id)
{
return BadRequest();
}
_dbContext.Entry(brand).State = EntityState.Modified;
try
{
await _dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (BrandAvailable != null)
{
return NotFound();
}
else
{
throw;
}
}
return Ok();
}
private bool BrandAvailable(int id)
{
return (_dbContext.Brands?.Any(b => b.Id == id)).GetValueOrDefault();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteBrand(int id)
{
try {
var result=await _dbContext.Brands.FindAsync(id);
if (result == null)
{
return NotFound();
}
_dbContext.Brands.Remove(result);
await _dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException) {
return NotFound();
}
return Ok();
}
}
}
Comments
Post a Comment