From 7c6efff0ebc42d81b7cad23f04c833232c80fb58 Mon Sep 17 00:00:00 2001 From: 0GiS0 Date: Fri, 9 Feb 2024 14:06:14 +0100 Subject: [PATCH] Refactor Hero class and repository --- Models/Hero.cs | 36 +++++++++++++++++++++++++++++++++- interfaces/IHeroRepository.cs | 2 +- repositories/HeroRepository.cs | 8 ++++++-- 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/Models/Hero.cs b/Models/Hero.cs index 8dc6151..0378fcb 100644 --- a/Models/Hero.cs +++ b/Models/Hero.cs @@ -1,10 +1,44 @@ +using System.ComponentModel.DataAnnotations; + namespace tour_of_heroes_api.Models { + /// + /// Represents a hero in the Tour of Heroes application. + /// public class Hero { + /// + /// Initializes a new instance of the class with the specified name and alter ego. + /// + /// The name of the hero. + /// The alter ego of the hero. + public Hero(string Name, string AlterEgo) + { + this.Name = Name; + this.AlterEgo = AlterEgo; + } + + /// + /// Gets or sets the ID of the hero. + /// + [Key] public int Id { get; set; } + + /// + /// Gets or sets the name of the hero. + /// + [Required] public string Name { get; set; } + + /// + /// Gets or sets the alter ego of the hero. + /// + [Required] public string AlterEgo { get; set; } - public string Description { get; set; } + + /// + /// Gets or sets the description of the hero. + /// + public string? Description { get; set; } } } \ No newline at end of file diff --git a/interfaces/IHeroRepository.cs b/interfaces/IHeroRepository.cs index 63b8c8c..9f0a532 100644 --- a/interfaces/IHeroRepository.cs +++ b/interfaces/IHeroRepository.cs @@ -17,7 +17,7 @@ public interface IHeroRepository /// /// The ID of the hero. /// The hero with the specified ID. - Hero GetById(int id); + Hero? GetById(int id); /// /// Adds a new hero. diff --git a/repositories/HeroRepository.cs b/repositories/HeroRepository.cs index 6679af8..813a91d 100644 --- a/repositories/HeroRepository.cs +++ b/repositories/HeroRepository.cs @@ -9,7 +9,7 @@ public class HeroRepository : IHeroRepository public IEnumerable GetAll() => _context.Heroes.ToList(); - public Hero GetById(int id) => _context.Heroes.FirstOrDefault(h => h.Id == id); + public Hero? GetById(int id) => _context.Heroes.FirstOrDefault(h => h.Id == id); public void Add(Hero hero) { @@ -19,7 +19,11 @@ public void Add(Hero hero) public void Delete(int id) { - _context.Heroes.Remove(GetById(id)); + var hero = GetById(id); + + if (hero == null) return; + + _context.Heroes.Remove(hero); _context.SaveChanges(); }