public void Remove(Owner owner) { using (var context = new BakeryContext()) { context.Owners.Remove( context.Owners.Find(owner.Id.Id) ); try { context.SaveChanges(); } catch (DbUpdateException e) { throw new RepositoryException(e.Message, e); } } }
public void Save(Owner owner) { using (var context = new BakeryContext()) { var existingDto = context.Owners .Include("Phones") .Include("OwnerAddress") .FirstOrDefault(o => o.Id == owner.Id.Id) ?? new Context.Shop.Owner(); var newDto = Mapper.ToDto(owner); var id = newDto.Id; if (context.Owners.Any(e => e.Id == id)) { var updatedPhones = newDto.Phones.ToList(); var existingPhones = existingDto.Phones.ToList(); var addedPhones = updatedPhones.Except(existingPhones).ToList(); var deletedPhones = existingPhones.Except(updatedPhones).ToList(); var modifiedPhones = updatedPhones.Except(addedPhones).ToList(); addedPhones.ForEach(phn => context.Entry(phn).State = EntityState.Added); deletedPhones.ForEach(phn => context.Entry(phn).State = EntityState.Deleted); foreach (var phone in modifiedPhones) { var existingPhone = context.OwnerPhones .FirstOrDefault(phn => phn.Equals(phone)); if (existingPhone == null) { continue; } var phoneEntry = context.Entry(existingPhone); phoneEntry.CurrentValues.SetValues(phone); } var ownerEntry = context.Entry(existingDto); ownerEntry.CurrentValues.SetValues(newDto); var ownerAddressEntry = context.Entry(existingDto.OwnerAddress); ownerAddressEntry.CurrentValues.SetValues(newDto.OwnerAddress); } else { context.Owners.Add(newDto); } try { context.SaveChanges(); } catch (DbUpdateException e) { throw new RepositoryException(e.Message, e); } } }