Guest User

removeTown

a guest
Jul 5th, 2020
93
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static string RemoveTown(SoftUniContext context)
  2. {
  3. var townToDelete = context
  4. .Towns
  5. .First(t => t.Name == "Seattle");
  6.  
  7. IQueryable<Address> addressesToDelete =
  8. context
  9. .Addresses
  10. .Where(a => a.TownId == townToDelete.TownId);
  11.  
  12. int addressesCount = addressesToDelete.Count();
  13.  
  14. IQueryable<Employee> employeesOnDeletedAddresses =
  15. context
  16. .Employees
  17. .Where(e => addressesToDelete.Any(a => a.AddressId == e.AddressId));
  18.  
  19. foreach (var employee in employeesOnDeletedAddresses)
  20. {
  21. employee.AddressId = null;
  22. }
  23.  
  24. foreach (var address in addressesToDelete)
  25. {
  26. context.Addresses.Remove(address);
  27. }
  28.  
  29. context.Remove(townToDelete);
  30.  
  31. context.SaveChanges();
  32.  
  33. return $"{addressesCount} addresses in Seattle were deleted";
  34.  
  35. }
RAW Paste Data