public async Task <IHttpActionResult> AddShareUserPet(ShareUserPetViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userId = User.Identity.GetUserId <int>(); var user = await DbContext.Users .SingleOrDefaultAsync(o => o.Id.Equals(userId)); var grantUser = await DbContext.Users .SingleOrDefaultAsync(o => o.Id.Equals(model.ShareUserId)); var sharePetIds = model.SharePets.Select(x => x.PetId).ToList(); var userPets = DbContext.Pets .Where(x => x.DateDeleted == null) .Where(o => o.OwnerId == userId) .Where(x => sharePetIds.Contains(x.Id)) .ToList(); var shareUserExist = user.ShareUserPets .Where(x => x.ShareUserId == model.ShareUserId && x.ShareUserType == model.ShareUserType) .SingleOrDefault(); if (user == null || grantUser == null || user.Id == grantUser.Id || sharePetIds.Count != userPets.Count) { return(NotFound()); } if (shareUserExist != null) { return(BadRequest("The user is already associated with this account.")); } using (var transactionContext = DbContext.Database.BeginTransaction()) { try { var shareUserPet = Mapper.Map <ShareUserPet>(model); user.ShareUserPets.Add(shareUserPet); await DbContext.SaveChangesAsync(); transactionContext.Commit(); return(Ok(Mapper.Map <ShareUserPetViewModel>(shareUserPet))); } catch (Exception e) { return(InternalServerError(e)); } } }
public async Task <IHttpActionResult> TransferShareUserPet(ShareUserPetViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userId = User.Identity.GetUserId <int>(); var user = await DbContext.Users .SingleOrDefaultAsync(o => o.Id.Equals(userId)); var grantUser = await DbContext.Users .SingleOrDefaultAsync(o => o.Id.Equals(model.ShareUserId)); var sharePetIds = model.SharePets.Select(x => x.PetId).ToList(); var userPets = DbContext.Pets .Where(x => x.DateDeleted == null) .Where(o => o.OwnerId == userId) .Where(x => sharePetIds.Contains(x.Id)) .ToList(); if (user == null || grantUser == null || user.Id == grantUser.Id || sharePetIds.Count != userPets.Count) { return(NotFound()); } var destinationUser = DbContext.Users .SingleOrDefault(x => x.Id == grantUser.Id); if (destinationUser == null) { return(BadRequest("The user is not a member.")); } using (var transactionContext = DbContext.Database.BeginTransaction()) { try { userPets.ForEach(r => r.OwnerId = destinationUser.Id); await DbContext.SaveChangesAsync(); //removing all shared settings await DbContext.SharePets .Where(x => sharePetIds.Contains(x.PetId)) .ForEachAsync(e => DbContext.SharePets.Remove(e)); await DbContext.SaveChangesAsync(); transactionContext.Commit(); return(Ok()); } catch (Exception e) { return(InternalServerError(e)); } } }