API development using .NET Core - ProductManagmentCRUD
1) Create Database and Table as mentioned below queries
create table products(ProdId int Primary key, ProductName varchar(20), Price int )
insert into products (ProdId, ProductName, Price ) values (1,'Laptop','45000');
insert into products (ProdId, ProductName, Price ) values (2,'Mouse','500');
insert into products (ProdId, ProductName, Price ) values (3,'Router','1800');
select * from products;
2) Create ASP.NET Core API Project
Install NuGet Packages
3) AppSettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DbConnection": "Server=Server_name; Database=ProductManagementCrud; User Id=sa; password=oj#$kdfn; TrustServerCertificate=True;"
},
"AllowedHosts": "*"
}
4) Model - Product.cs
namespace ProductManagmentCRUD.Models
{
public class Product
{
public int ProdId { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
}
}
5) AppDbContext.cs
using Microsoft.EntityFrameworkCore;
using ProductManagmentCRUD.Models;
namespace ProductManagmentCRUD.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasKey(p => p.ProdId);
modelBuilder.Entity<Product>().Property(p => p.ProductName).HasMaxLength(20);
}
}
}
6) Program.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using ProductManagmentCRUD.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnection")));
builder.Services.AddControllers();
// Add Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
8) Controller
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using ProductManagmentCRUD.Data;
using ProductManagmentCRUD.Models;
namespace ProductManagmentCRUD.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : Controller
{
private readonly AppDbContext _appDbContext;
public ProductController (AppDbContext context)
{
_appDbContext = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _appDbContext.Products.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _appDbContext.Products.FindAsync(id);
if (product == null)
return NotFound();
return product;
}
[HttpPost]
public async Task<ActionResult<Product>> CreateProduct(Product product)
{
_appDbContext.Products.Add(product);
await _appDbContext.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.ProdId }, product);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateProduct(int id, Product product)
{
if (id != product.ProdId)
return BadRequest();
_appDbContext.Entry(product).State = EntityState.Modified;
await _appDbContext.SaveChangesAsync();
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _appDbContext.Products.FindAsync(id);
if (product == null)
return NotFound();
_appDbContext.Products.Remove(product);
await _appDbContext.SaveChangesAsync();
return NoContent();
}
}
}
9) AppDbContext
using Microsoft.EntityFrameworkCore;
----------------------------------------------
SCREENSHOTS OF API METHODS
Comments
Post a Comment