Add pizza classes
Add Pizza and PizzaService classes
Before you start to implement the form to manage pizzas, you need to have a data store that you can perform operations on.
A model class is needed to represent a pizza in inventory.
The model contains properties that represent the characteristics of a pizza.
The model is used to pass data in the web app and to persist pizza options in the data store.
In this unit, that data store will be a simple local in-memory caching service.
In a real-world application, you would consider using a database, such as SQL Server, with Entity Framework Core.
Create a pizza model
Run the following command in your project's root directory to create a
Models
folder:mkdir Models
Select the
Models
folder in the file explorer and add a new File calledPizza.cs
.The project root now contains a Models directory with an empty Pizza.cs file. The directory name Models is a convention.
Add the following code to Models/Pizza.cs to define a pizza. Save your changes.
using System.ComponentModel.DataAnnotations; namespace RazorPagesPizza.Models; public class Pizza { public int Id { get; set; } [Required] public string? Name { get; set; } public PizzaSize Size { get; set; } public bool IsGlutenFree { get; set; } [Range(0.01, 9999.99)] public decimal Price { get; set; } } public enum PizzaSize { Small, Medium, Large }
Add data service
Run the following command in your project's root directory to create a
Services
folder:mkdir Services
Select the folder in the file explorer and add a new file called
PizzaService.cs
.Add the following code to Services/PizzaService.cs to create an in-memory pizza data service. Save your changes.
using RazorPagesPizza.Models; namespace RazorPagesPizza.Services; public static class PizzaService { static List<Pizza> Pizzas { get; } static int nextId = 3; static PizzaService() { Pizzas = new List<Pizza> { new Pizza { Id = 1, Name = "Classic Italian", Price=20.00M, Size=PizzaSize. Large, IsGlutenFree = false }, new Pizza { Id = 2, Name = "Veggie", Price=15.00M, Size=PizzaSize.Small, IsGlutenFree = true } }; } public static List<Pizza> GetAll() => Pizzas; public static Pizza? Get(int id) => Pizzas.FirstOrDefault(p => p.Id == id); public static void Add(Pizza pizza) { pizza.Id = nextId++; Pizzas.Add(pizza); } public static void Delete(int id) { var pizza = Get(id); if (pizza is null) return; Pizzas.Remove(pizza); } public static void Update(Pizza pizza) { var index = Pizzas.FindIndex(p => p.Id == pizza.Id); if (index == -1) return; Pizzas[index] = pizza; } }
Note: This service provides a simple in-memory data caching service with two pizzas by default that your web app will use for demo purposes.
Last updated