Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davepcallan/f29045c8eeb6368a21c470bf50db9736 to your computer and use it in GitHub Desktop.
Save davepcallan/f29045c8eeb6368a21c470bf50db9736 to your computer and use it in GitHub Desktop.
ChatGPT controller with injected repository example.
//Generate a .NET API ProductController which has hardcoded Products (in a repository
//which is injected into the ProductController constructor) and full crud actions
//using strongly typed DTOs which map to domain models using the explicit operator in C#.
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace ProductAPI.Controllers
{
public class ProductController : ApiController
{
private readonly IProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
// GET api/product
public IEnumerable<ProductDTO> Get()
{
return _productRepository.GetAll().Select(product => (ProductDTO)product);
}
// GET api/product/5
public ProductDTO Get(int id)
{
var product = _productRepository.GetById(id);
return (ProductDTO)product;
}
// POST api/product
public void Post(ProductDTO productDTO)
{
var product = (Product)productDTO;
_productRepository.Add(product);
}
// PUT api/product/5
public void Put(int id, ProductDTO productDTO)
{
var product = (Product)productDTO;
product.Id = id;
_productRepository.Update(product);
}
// DELETE api/product/5
public void Delete(int id)
{
_productRepository.Delete(id);
}
}
}
public class ProductDTO
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public static explicit operator ProductDTO(Product product)
{
return new ProductDTO
{
Id = product.Id,
Name = product.Name,
Price = product.Price
};
}
public static explicit operator Product(ProductDTO productDTO)
{
return new Product
{
Id = productDTO.Id,
Name = productDTO.Name,
Price = productDTO.Price
};
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product GetById(int id);
void Add(Product product);
void Update(Product product);
void Delete(int id);
}
public class ProductRepository : IProductRepository
{
private static readonly List<Product> Products = new List<Product>
{
new Product { Id = 1, Name = "Product 1", Price = 10.99m },
new Product { Id = 2, Name = "Product 2", Price = 20.99m },
new Product { Id = 3, Name = "Product 3", Price = 30.99m }
};
public IEnumerable<Product> GetAll()
{
return Products;
}
public Product GetById(int id)
{
return Products.SingleOrDefault(product => product.Id == id);
}
//often gets cut off at the end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment