因此,我遇到了一个与更新数据库相关的问题,其中包含我自己的实体
class WordEntity
{
public int ID { get; set; }
public string word { get; set; }
public int frequency { get; set; }
public override string ToString()
{
return word;
}
}
我已经用一些txt文件中的单词填充了它,并计算了它们出现的次数(对于每个单词)。现在我需要从另一个txt文件中添加更多的单词,并计算它们出现的次数。问题是编写LINQ语句,它必须更新现有的单词(它们的频率)并添加更多的新词。我使用了这个,但是EF抛出了一个异常,与.Concat
连接
var t = context.Words
`.Concat`(tempList)
.GroupBy(w => w.word)
.Select(w => new WordEntity() {word = w.Key, frequency = w.Sum(z => z.frequency)});
templist
是来自新txt文件的新词的List<WordEntity>
。请帮帮忙。
发布于 2020-09-27 21:27:18
您可以使用不同的策略,但本质上,您需要为新文件中的每个单词检查该单词是否已经存在于数据库中。如果不是,则需要添加一个(频率为1)。否则,您需要增加现有单词的频率。一种解决方案是这样的:
using var context = new MyContext();
foreach (var word in ReadWordsFromFile(filename))
{
var existingWord = await context.Words.SingleOrDefaultAsync(w => w.Word == word);
if (existingWord is null)
{
context.Add(new WordEntity { Word = word, Frequency = 1 });
}
else
{
existingWord.Frequency++;
}
}
await context.SaveChangesAsync();
您还可以(正如您所做的那样)尝试一次从数据库中读取所有实体,并在内存中完成整个操作:
var existingWords = await context.Words.ToDictionaryAsync(w => w.Word);
foreach (var word in ReadWordsFromFile(filename))
{
if (existingWords.ContainsKey(word))
existingWords[word].Frequency++;
else
{
var wordEntity = new WordEntity { Word = word, Frequency = 1 };
context.Add(wordEntity);
existingWords[word] = wordEntity;
}
}
这可能会更快(因为所有操作都是在内存中完成的),但随着数据库的增长,可能会出现问题,因为您将需要越来越多的内存来从数据库获取所有数据。第一个解决方案将只从数据库中获取实际需要的单词。
发布于 2020-09-28 04:54:06
虽然Jeroen的答案会起作用,但效率不是很高。假设单词" the“在文件中出现了10.000次,那么他将从数据库中获取频率10.000次,并添加+1
首先检查这个单词是否出现了10.000次,然后添加或更新频率+1000,这不是更好吗?
您可以使用以下命令来完成此操作:
IEnumerable<string> newWords = ReadWordsFromFile(...)
var newWordFrequencies = newWords.GroupBy(word => word,
// parameter resultSelector: from every key (which is a word, and all occurences
// of this word, make one new:
(key, wordsEqualToThisKey) => new
{
Word = key,
Count = wordsEqualToThisKey.Count(),
});
foreach (var newWord in newWordFrequencies)
{
// fetch the frequency from the database. if it exists: add count
var fetchedExistingWord = dbContext.Words
.Where(existingWord => existingWord.Word == newWord)
.FirstOrDefault();
if (fetchedExistingWord != null)
{
fetchedExistingWord.Frequency += newWord.Count;
}
else
{
// new Word is not in the database yet; add it
dbContext.Words.Add(new WordEntity
{
Word = newWord.Word,
Frequency = newWord.Count,
});
}
}
https://stackoverflow.com/questions/64088449
复制相似问题