using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public class AppDbContext : DbContext
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseInMemoryDatabase("ProductDb");
public class ProductService
private readonly AppDbContext _context;
public ProductService(AppDbContext context)
public async Task AddProductAsync(Product product)
_context.Products.Add(product);
await _context.SaveChangesAsync();
public async Task<List<Product>> GetAllProductsAsync()
return await _context.Products.ToListAsync();
public async Task<Product> GetProductByIdAsync(int id)
return await _context.Products.FindAsync(id);
public async Task UpdateProductAsync(Product product)
_context.Products.Update(product);
await _context.SaveChangesAsync();
public async Task DeleteProductAsync(int id)
var product = await _context.Products.FindAsync(id);
_context.Products.Remove(product);
await _context.SaveChangesAsync();
public static async Task Main(string[] args)
using var context = new AppDbContext();
var service = new ProductService(context);
var product = new Product { Name = "Laptop", Price = 1200 };
await service.AddProductAsync(product);
Console.WriteLine("Product added.");
var products = await service.GetAllProductsAsync();
Console.WriteLine("All Products:");
foreach (var p in products)
Console.WriteLine($"{p.Id}: {p.Name} - ${p.Price}");
await service.UpdateProductAsync(product);
Console.WriteLine("Product updated.");
await service.DeleteProductAsync(product.Id);
Console.WriteLine("Product deleted.");