public async Task <int> AddWordsToDictionary(Stream wordStream) { int wordsAdded = 0; // Dictionary corresponding to the to-be-added wordlist ActiveDictionary addDictionary; try { addDictionary = Loader.LoadDictionary(wordStream); } catch (FileLoadException) { // Empty, Abort return(0); } // Dictionary corresponding to the in-database wordlist var dbDictionary = context.GetWordDictionaryForContext(); var lettersToUpdate = addDictionary.GetAllDictionaryLetters().Select(dl => dl.Letter).ToList(); // Get the actual entities from the DB List <Letter> letters = await context.Letters.Where(letter => lettersToUpdate.Contains(letter.Character)) .OrderBy(letter => letter.Character) .ToListAsync(); try { foreach (var letter in letters) { var addTheseWords = addDictionary.GetDictionaryWordsStartingWith(letter.Character) .Select(word => new Word() { TheWord = word, Letter = letter }); wordsAdded += context.AddWordEntities(addTheseWords); } } finally { await context.SaveChangesAsync(); } // Changes must be saved prior to getting updated states. fml -.- try { foreach (var letter in letters) { // Update Letter Statistics var updatedLetterStats = DictionaryLetter.InitializeDictionaryLetter(letter.Character, dbDictionary); letter.AverageCharacters = updatedLetterStats.AverageCharacterCount; letter.CountBeginningWith = updatedLetterStats.NumberWordsBeginningWith; letter.CountEndingWith = updatedLetterStats.NumberWordsEndingWith; context.Letters.Update(letter); } } finally { await context.SaveChangesAsync(); } return(wordsAdded); }