public static void Main() { var exit = false; while (!exit) { Console.WriteLine("What do you want to do?\n[new|list|update|delete|exit] [dog|person|ownership]"); var command = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); Type entityType; object entity; using var dbContext = new DogFarmDbContext(); switch (command[0]) { case "new": entityType = GetEntityType(); entity = Activator.CreateInstance(entityType); SetPropertiesOrSave(entity); dbContext.Add(entity); dbContext.SaveChanges(); break; case "list": entityType = GetEntityType(); var entities = (IEnumerable)typeof(DogFarmDbContext).GetMethod(nameof(DogFarmDbContext.Set)).MakeGenericMethod(entityType).Invoke(dbContext, null); if (entities.Cast <object>().Count() == 0) { Console.WriteLine($"No entities stored of type {entityType}."); } else { foreach (var item in entities) { Console.WriteLine(item); } } break; case "update": entityType = GetEntityType(); entity = dbContext.Find(entityType, ReadId()); SetPropertiesOrSave(entity); dbContext.SaveChanges(); break; case "delete": entityType = GetEntityType(); entity = dbContext.Find(entityType, ReadId()); dbContext.Remove(entity); dbContext.SaveChanges(); break; case "exit": exit = true; break; default: Console.WriteLine($"Unknown command: '{command}'."); break; }
private static void DeleteDog(int dogId) { using var dbContext = new DogFarmDbContext(); var dog = dbContext.Dogs.Find(dogId); dbContext.Dogs.Remove(dog); dbContext.SaveChanges(); }
private static void UpdateDogBirthDate(int dogId, DateTime?birthDate) { using var dbContext = new DogFarmDbContext(); var dog = dbContext.Dogs.Find(dogId); dog.BirthDate = birthDate; dbContext.SaveChanges(); }
private static void PrintDogs() { using var dbContext = new DogFarmDbContext(); var dogs = dbContext.Dogs.ToList(); if (dogs.Count == 0) { Console.WriteLine("No dogs are stored in the database."); } else { foreach (var dog in dogs) { Console.WriteLine(dog); } } Console.WriteLine(); }
private static void AddDogToDatabase(Dog newDog) { using var dbContext = new DogFarmDbContext(); dbContext.Dogs.Add(newDog); dbContext.SaveChanges(); }