private async Task <T> AddOrUpdateItem <T>(T item, Func <T, object[]> keysFunc, UpdateFunc <T> updater) where T : class { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (keysFunc == null) { throw new ArgumentNullException(nameof(keysFunc)); } if (updater == null) { throw new ArgumentNullException(nameof(updater)); } // Try to find the item var foundItem = await _context.Set <T>().FindAsync(keysFunc(item)); if (foundItem != null) { var entry = _context.Entry(foundItem); if (entry.State == EntityState.Added) { return(foundItem); } entry.State = EntityState.Modified; updater(foundItem, item, entry); return(foundItem); } _context.Add(item); return(item); }
/// <inheritdoc /> public async Task SaveUserData(UserSaveDataDto data) { // Get the user User user; var baseQuery = _context.Users.Include(u => u.UserPrimeItemSaveData).Include(u => u.UserPrimePartIngredientSaveData); if (_userData.IsAnonymous) { user = await baseQuery.FirstOrDefaultAsync(u => u.AnonymousId == _userData.AnonymousId); if (user == null) { user = new User() { AnonymousId = _userData.AnonymousId, UserPrimeItemSaveData = new List <UserPrimeItemSaveData>(), UserPrimePartIngredientSaveData = new List <UserPrimePartIngredientSaveData>(), }; _context.Users.Add(user); } } else { user = await baseQuery.FirstOrDefaultAsync(u => u.Email == _userData.Email); } // Clear all user data user.UserPrimeItemSaveData.Clear(); user.UserPrimePartIngredientSaveData.Clear(); // Fill 'er up again foreach (var primeItem in data.PrimeItems) { if (primeItem.Value.IsChecked) { user.UserPrimeItemSaveData.Add(new UserPrimeItemSaveData() { UserId = user.Id, PrimeItemId = primeItem.Key, IsChecked = primeItem.Value.IsChecked, }); } foreach (var primePart in primeItem.Value.PrimePartIngredients) { if (primePart.Value.CheckedCount > 0) { user.UserPrimePartIngredientSaveData.Add(new UserPrimePartIngredientSaveData() { UserId = user.Id, PrimePartIngredientId = primePart.Key, CheckedCount = primePart.Value.CheckedCount, }); } } } // Make sure User gets updated _context.Entry(user).State = EntityState.Modified; // Save await _context.SaveChangesAsync(); }