这是我的代码:
public Dictionary<int, CharacterActionBarSpells> AllcharacterActionBarSpells = new Dictionary<int, CharacterActionBarSpells>();
private void Test(){
int lastInsertID = Convert.ToInt32(cmdInsert.LastInsertedId);
foreach(var item in AllcharacterActionBarSpells)
{
Console.WriteLine("KEY:" + item.Key + " ID: " + item.Value.id + " spell " + item.Value.spell + " slot: " + item.Value.spell);
}
Console.WriteLine("Last inserted id: " + lastInsertID);
AllcharacterActionBarSpells.Add(lastInsertID, new CharacterActionBarSpells()
{
id = lastInsertID,
character_id = Convert.ToInt32(abcSpells["character_id"]),
spell = Convert.ToInt32(abcSpells["spell"]),
actionbar_group = Convert.ToInt32(abcSpells["actionbar_group"]),
slot = Convert.ToInt32(abcSpells["new_slot"])
});
}
这是控制台输出:
KEY:1 ID: 1 spell 1 slot: 1
KEY:2 ID: 2 spell 2 slot: 2
KEY:3 ID: 3 spell 3 slot: 3
KEY:4 ID: 4 spell 4 slot: 4
KEY:19 ID: 19 spell 2 slot: 2
KEY:20 ID: 20 spell 3 slot: 3
KEY:21 ID: 21 spell 3 slot: 3
Last inserted id: 22
正如您所见AllcharacterActionBarSpells.Add(lastInsertID,
我总共有七条记录。最后一个密钥为21
。所以在那之后我试图在字典中添加新记录但是我收到以下错误:
System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'
基本上lastInsertID
是MySQL插入后的最后一个插入ID。如果它很重要,我确定AllcharacterActionBarSpells
不是空的。我认为没有必要将字典留空以便将数据放入其中,我是否正确?
我做错了什么?为什么我不能在字典中添加新记录以及为什么我收到此错误?