Part I [Read] | Part II [Create, Update, and Delete]
Get all of the installed templates
dotnet new --list
Create a new project web API on the command line
dotnet new webapi -o Cousrse01
dotnet run
Command help
dotnet new webapi -h
dotnet new webapi -minimal -o Cousrse01 // Without Controller
Create Controller and Models for first Route Api
// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Cousrse01.API.Models;
namespace Cousrse01.Controllers;
[Route("api/[controller]")]
[ApiContorller]
public class ProductsController : ControllerBase {
[HttpGet]
public ActionResult AllProducts()
{
return Ok(_context.Products.ToArray());
}
[HttpGet("{id}")]
public ActionResult GetProduct(int id)
{
var product = _context.Products.Find(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
dotnet new class --name Category --output Models
// Models/Category.cs
namespace Cousrse01.API.Models;
public class Category
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public virtual ICollection<Product> Products { get; set; } = null!;
}
dotnet new class --name Product --output Models
// Models/Product.cs
namespace Cousrse01.API.Models;
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string? Sku { get; set; }
public decimal Price { get; set; }
public string? Description { get; set; }
//is available
public bool IsAvailable { get; set; }
// Category Id
public int CategoryId { get; set; }
public virtual Category Category { get; set; } = null!;
}
Add Microsoft.EntityFrameworkCore InMemory to project
dotnet add package Microsoft.EntityFrameworkCore.InMemory
Create Database Context
dotnet new class --name ShopContext --output Models
// Models/ShopContext.cs
using Microsoft.EntityFrameworkCore;
namespace Cousrse01.API.Models;
public class ShopContext :DbContext
{
public ShopContext(DbContextOptions<ShopContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>()
.HasMany(c => c.Products)
.WithOne(e => e.Category)
.HasForeignKey(e => e.CategoryId)
.OnDelete(DeleteBehavior.Cascade);
// TODO: refactor
// modelBuilder.seed();
modelBuilder.Entity<Category>().HasData(
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name = "Clothes" },
new Category { Id = 3, Name = "Grocery" }
);
modelBuilder.Entity<Product>().HasData(
new Product { Id = 1, Name = "Laptop", Price = 1000, CategoryId = 1 },
new Product { Id = 2, Name = "T-Shirt", Price = 10, CategoryId = 2 },
new Product { Id = 3, Name = "Milk", Price = 2, CategoryId = 3 }
);
}
public DbSet<Category> Categories { get; set; } = null!;
public DbSet<Product> Products { get; set; } = null!;
Making the API asynchronous [Task, Async, await]
// Controllers/ProductsController.cs
// Rewrite to make asynchronous
using Cousrse01.API.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Cousrse01.Controllers;
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
private readonly ShopContext _context;
public ProductsController(ShopContext context)
{
_context = context;
_context.Database.EnsureCreated();
}
[HttpGet]
public async Task<ActionResult> AllProducts()
{
//return "Get Products";
return Ok(await _context.Products.ToArrayAsync());
}
[HttpGet("{id}")]
public async Task<ActionResult> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
Run and check the Product list and single by id
dotnet run
# The port is sample
http://localhost:5027/swagger/index.html
In the next part, I will complete Create, Update, and Delete.
Part II ( Create, Update, and Delete) >>