如何解决我如何使用LINQ更新数据库
所以,我有一个问题,与更新数据库有关,其中包含我自己的实体
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>
。
请帮忙。
解决方法
您可以使用不同的策略,但是实质上,您需要针对新文件中的每个单词检查该单词是否已存在于数据库中。如果不是,则需要添加一个(频率为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;
}
}
这可能会更快(因为所有操作都在内存中完成),但是随着数据库的增长可能会出现问题,因为您将需要越来越多的内存来从数据库中获取所有数据。第一种解决方案只会从数据库中获取实际需要的单词。
,尽管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,});
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。