Step 1: Create entity
class Product
{
public int ProductID {get;set;}
public string ProductName {get;set;}
}
class Category
{
public int CategoryID {get;set;}
public string CategoryName {get;set;}
public string Description {get;set;}
}
Step 2: create DBContext
class ProductContext : DbContext
{
public ProductContext(DbContextOptions<ProductContext> options):base(options)
{
}
public DbSet<Product> Products {get;set;}
public DbSet<Category> Category {get;set;}
public override void OnModelCreating(ModelBuilder modelbuilder)
{
modeulBuilder.Entity<Category>().HasData(
new Category{
CategoryID=1,
Name = "Electronics",
Description = "electronics items"
},
new Category{
CategoryID=2,
Name = "Clothes",
Description = "dresses"
})
}
}
Step 3: Create repository
interface IProductRepository
{
IEnumerable<Product> getProducts();
Product getProductById(int productid);
void InsertProduct(Product product);
void UpdateProduct(Product product);
void DeleteProduct(int productid);
void Save();
}
class ProductRepository : IProductRepository
{
ProductContext _productContext
public ProductRepository (ProductContext productContext)
{
_productContext = _productContext;
}
IEnumerable<Product> getProducts()
{
return _productContext.Products.ToList();
}
Product getProductById(int productid)
{
return _productContext.Products.Find(productid);
}
void InsertProduct(Product product);
{
_productContext.Add(product);
Save();
}
void UpdateProduct(Product product)
{
_dbcontext.Entry(product).State = EntityState.Modified;
Save();
}
void DeleteProduct(int productid)
{
var product = _dbContext.Products.Find(productID);
_dbcontext.Products.Remove(product);
Save();
}
void Save()
{
_dbContext.SaveChanges();
}
}
Step 4: add connection string in appsettings.json
Step 5: register DB context & repository in startup.js
services.AddDbContext<ProductContext>(o => o.useSqlServer(Configurtion.GetConnectionString("ProductDB"));
services.AddTransient<IProductRepository,ProductRepository>();
6) create controller and inject repository in constructor
[Route("api\[controller]"]
[ApiController]
public class ProductController: ControllerBase
{
ProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
[HttpGet]
public IActionResult GetProducts()
{
var product = _productRepository.getProducts();
return new OkObjectResult(product);
}
}
7) Extended the controller using http verb (get, post, put, delete)
Comments
So good to find another person with some unique thoughts on this issue.
Really.. many thanks for starting this up. This site is one thing
that is needed on the internet, someone with a bit of originality!