You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.3 KiB
79 lines
2.3 KiB
using Microsoft.AspNetCore.Http.HttpResults;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using WebAPIWithEF.Data;
|
|
using WebAPIWithEF.Models;
|
|
|
|
namespace WebAPIWithEF.Services
|
|
{
|
|
public class PizzaService
|
|
{
|
|
private readonly PizzaContext _context;
|
|
|
|
public PizzaService(PizzaContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
public IEnumerable<Pizza> GetAll()
|
|
{
|
|
return _context.Pizzas
|
|
.AsNoTracking() // just read service (not track changes of the entity)
|
|
.ToList();
|
|
}
|
|
|
|
public Pizza? GetById(int id)
|
|
{
|
|
return _context.Pizzas
|
|
.Include(p => p.Toppings)
|
|
.Include(p => p.Sauce)
|
|
.AsNoTracking()
|
|
.SingleOrDefault(p => p.Id == id);
|
|
}
|
|
|
|
public Pizza? Create(Pizza newPizza)
|
|
{
|
|
_context.Pizzas.Add(newPizza);
|
|
_context.SaveChanges();
|
|
|
|
return newPizza;
|
|
}
|
|
|
|
public void AddTopping(int PizzaId, int ToppingId)
|
|
{
|
|
var pizzaToUpdate = _context.Pizzas.Include(p => p.Toppings).SingleOrDefault(p => p.Id == PizzaId);
|
|
var toppingToAdd = _context.Toppings.Find(ToppingId);
|
|
if (pizzaToUpdate is null || toppingToAdd is null)
|
|
throw new InvalidOperationException("Pizza or topping does not exist");
|
|
|
|
if (pizzaToUpdate.Toppings is null)
|
|
pizzaToUpdate.Toppings = new List<Topping>();
|
|
|
|
pizzaToUpdate.Toppings.Add(toppingToAdd);
|
|
|
|
_context.SaveChanges();
|
|
}
|
|
|
|
public void UpdateSauce(int PizzaId, int SauceId)
|
|
{
|
|
var pizzaToUpdate = _context.Pizzas.Find(PizzaId);
|
|
var sauceToUpdate = _context.Sauces.Find(SauceId);
|
|
if (pizzaToUpdate is null || sauceToUpdate is null)
|
|
throw new InvalidOperationException("Pizza or sauce does not exist");
|
|
|
|
pizzaToUpdate.Sauce = sauceToUpdate;
|
|
|
|
_context.SaveChanges();
|
|
}
|
|
|
|
public void DeleteById(int id)
|
|
{
|
|
var pizzaToDelete = _context.Pizzas.Find(id);
|
|
if (pizzaToDelete is null)
|
|
return;
|
|
|
|
_context.Pizzas.Remove(pizzaToDelete);
|
|
|
|
_context.SaveChanges();
|
|
}
|
|
}
|
|
}
|
|
|