Выдает ошибку «данный ключ отсутствует в словаре» при нажатии на Q,W… работают только клавиши от D1 до D0 и backsapace.
Вопрос: почему выдает ошибку, вроде же верно все?
public enum Notes
{
Do1, Re1, Mi1, Fa1, Col1, La1, Si1,
Do2, Re2, Mi2, Fa2, Col2, La2, Si2,
Do3, Re3, Mi3, Fa3, Col3, La3, Si3,
Do4, Re4, Mi4, Fa4, Col4, La4, Si4,
Do5, Re5, Mi5, Fa5, Col5, La5, Si5, Do6,
DoSharp1, ReSharp1, FaSharp1, ColSharp1, LaSharp1,
DoSharp2, ReSharp2, FaSharp2, ColSharp2, LaSharp2,
DoSharp3, ReSharp3, FaSharp3, ColSharp3, LaSharp3,
DoSharp4, ReSharp4, FaSharp4, ColSharp4, LaSharp4,
DoSharp5, ReSharp5, FaSharp5, ColSharp5, LaSharp5
}
private Dictionary<Notes, MediaPlayer> sounds = new Dictionary<Notes, MediaPlayer>();
private Dictionary<Keys, bool> pressStates = new Dictionary<Keys, bool>();
private Dictionary<Keys, Notes> KeySounds = new Dictionary<Keys, Notes>
{
{ Keys.D1, Notes.Do1 },
....
//для каждой ноты перечисления Notes задаем клавишу клавиатуры
....
{ Keys.NumPad9, Notes.LaSharp5 }
};
private void Form1_Load(object sender, EventArgs e)
{
//Инициализируем словари
foreach (Notes s in Enum.GetValues(typeof(Notes)).Cast<Notes>())
{
sounds.Add(s, new MediaPlayer());
pressStates.Add((Keys)s, false);
}
//Наполняем словарь звуками
sounds[Notes.Do1].Open(new Uri("s//_1.wav", UriKind.Relative));
....
//Для каждой ноты задаем звуковой файл
....
sounds[Notes.LaSharp5].Open(new Uri("s//25.wav", UriKind.Relative));
}
private void Form1_KeyDown(Object sender, KeyEventArgs e)
{
if (!KeySounds.ContainsKey(e.KeyCode)) return;
if (!pressStates[e.KeyCode])
{
pressStates[e.KeyCode] = true;
PlaySound(KeySounds[e.KeyCode]);
}
}
private void Form1_KeyUp(Object sender, KeyEventArgs e)
{
if (!KeySounds.ContainsKey(e.KeyCode)) return;
if (pressStates[e.KeyCode])
{
pressStates[e.KeyCode] = false;
StopSound(KeySounds[e.KeyCode]);
}
}
Trying to get simple count from table results in exception bellow.
Tried different select statemens which also makes exception: «SELECT * FROM goods«, but «SELECT col1, col2 FROM goods» — works without exception. What am I doing wrong? From workbench these selects works.
The given key was not present in the dictionary.
System.Collections.Generic.KeyNotFoundException: The given key was not
present in the dictionary. at
System.Collections.Generic.Dictionary`2.get_Item(TKey key) at
MySql.Data.MySqlClient.MySqlField.SetFieldEncoding() at
MySql.Data.MySqlClient.NativeDriver.GetColumnData(MySqlField field)
at MySql.Data.MySqlClient.NativeDriver.GetColumnsData(MySqlField[]
columns) at MySql.Data.MySqlClient.Driver.GetColumns(Int32 count)
at MySql.Data.MySqlClient.ResultSet.LoadColumns(Int32 numCols) at
MySql.Data.MySqlClient.ResultSet..ctor(Driver d, Int32 statementId,
Int32 numCols) at MySql.Data.MySqlClient.Driver.NextResult(Int32
statementId, Boolean force) at
MySql.Data.MySqlClient.MySqlDataReader.NextResult() at
MySql.Data.MySqlClient.MySqlDataReader.Close() at
MySql.Data.MySqlClient.MySqlCommand.ResetReader() at
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior
behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at MySqlSybaseComparer.DbTester.Test(String& error) in
c:MySqlSybaseComparerDbTester.cs:line 68
code snippet:
using (MySqlConnection conn = new MySqlConnection(ConStrMySql))
{
try
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand("SELECT count(*) FROM goods", conn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
MessageBox.Show(reader[0].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.ToString(););
}
conn.Close();
}
Connection string to DB: Server=localhost; Database=art; Uid=ramunas; Pwd=xxxx; AllowUserVariables=True;
asked Jan 30, 2017 at 6:22
4
Year 2017
I have solved your same error simply adding the charset to the connection string:
Server=myServer;Port=3306;Database=myDB15;User ID=usr33;Password=usr33P;CharSet=utf8;
In my case I’m using MySql Connector for .Net version 6.9.3. to connect to 30 equal databases with the same structure, same collation (utf8_unicode_ci) and different table contents.
When I use the MySqlCommand.ExecuteReader() method to select content from user table, in some databases (4 of 30) a got the same error The given key was not present in the dictionary.
Year 2022
Some years later I had the same problem with ObjectContext.ExecuteStoreQuery(), but right now using MySql.Data and MySql.Data.EntityFramework both on version 8.0.27 and when migrating a database from MySQL 5.7.38 to 8.0.28 or 8.0.30.
Adding CharSet or Allow User Variables to the connection string didn’t work (and it wasn’t possible to change my SELECT or Server settings).
Only updating MySql.Data and MySql.Data.EntityFramework to version 8.0.30 solved the problem.
answered Aug 4, 2017 at 7:26
Rafael NetoRafael Neto
9669 silver badges15 bronze badges
1
After spending 5 hours researching how to fix it!!!.. i finally figured it out… all you need to do is to make sure that your ‘MySql.Data.dll’ is up to date! you can download it somewhere. or you can find it here C:Program Files (x86)MySQLMySQL Installer for WindowsMySql.Data.dll.. 
answered Jul 23, 2018 at 8:29
1
Code is correct and all suggestion also should work. Just removed «collation-server» settings and restarted server and everything works as expected.
answered Jan 31, 2017 at 6:56
RamunasRamunas
9751 gold badge11 silver badges19 bronze badges
Try using
SELECT count(*) as count FROM goods
answered Jan 30, 2017 at 6:28
Ali BaigAli Baig
3,8094 gold badges33 silver badges47 bronze badges
0
In place of this statement:
using (MySqlCommand cmd = new MySqlCommand("SELECT count(*) FROM goods", conn))
Use:
using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM goods", conn))
and then convert it to int value by using ExecuteScalar(). Something like this:
int count = Convert.ToInt32(cmd.ExecuteScalar());
answered Jan 30, 2017 at 7:14
AsthaUndefinedAsthaUndefined
1,1111 gold badge11 silver badges24 bronze badges
2
I had same problem using .net core 2.1, mysql, nhibernate.
After i added "Allow User Variables=True" to connection string in appsettings.json my problem solved.
answered Oct 19, 2018 at 13:42
For anyone with the error «the given key ‘0’ was not found in the dictionary», it seems it’s looking for the MySQL DLL. Adding MySql.Data through your package manager or adding the DLL manually from the connector should solve it.
lee-m
2,27317 silver badges29 bronze badges
answered Jul 26, 2022 at 5:46
I tried all of these answers and none helped me.
I eventually tracked it down. The message was that .NET does not support the characterset (in my case utf8mb3) that the database was reporting.
Changed the default charset of the database and it worked perfectly.
answered Jul 16, 2021 at 0:09
Do update your mysql connector for .net, Then remove the old reference mysql.data.dll in your application project and add the updated one from program files(x86)/mysql/MySQL Connector Net 8.0.26Assembliesv4.5.2MySql.Data.dll
answered Jul 26, 2021 at 10:54
You may try going to «Server explorer» and delete the instance of your server that you are trying to connect. Once the instance is deleted trying connecting to the database once again with correct credentials. And if you are working with ADO.NET model be careful the versions of component that you are installing and referencing.
answered Mar 12, 2022 at 3:02
To get compatability you will need to use specific versions of the MySql.EntityFrameworkCore, MySql Connector/NET and entity framework to avoid these issues.
See https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-scaffold-example.html for examples
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.4" />
</ItemGroup>
Update the entity framework tool with
dotnet tool update --global dotnet-ef
The scaffolding command should look like
dotnet ef dbcontext scaffold "Server=[Host];Database=[DBName];User Id=[Username];Password=[Password];" MySql.EntityFrameworkCore -o [OutputContextName] --no-pluralize --no-onconfiguring -f
For details check out https://learn.microsoft.com/en-us/ef/core/cli/dotnet and search for dotnet ef dbcontext scaffold
answered Nov 2, 2022 at 8:00
XavierXavier
1,3836 silver badges6 bronze badges
use Database name in your query and Port in connection String
strMySqlConnection =
"server=localhost;Port=3306; user id=root; password=; database=art;
pooling=false;Charset = utf8 ;";
SELECT * FROM goods ==> SELECT * FROM `art`.`goods`
Update MySql.Data & use .Netframework 4.6
answered Apr 6 at 6:01
in my case i use MySQL Connector NET 6.3.0 and the solution that i got is to change connection string key
from
Server=127.0.0.1;Uid=root;Pwd=xxxx;Database=dbname;CharSet=utf8
to this
server=127.0.0.1;user id=root;password=xxxx;database=dbname;charset=utf8;pooling=false
answered Mar 5, 2020 at 14:12
1
|
Nibros 1 / 1 / 0 Регистрация: 19.04.2011 Сообщений: 22 |
||||
|
1 |
||||
|
13.01.2020, 14:59. Показов 7045. Ответов 23 Метки нет (Все метки)
Всем привет. Выкладываю кусок кода. Проблема: когда запускаю программа пишет ошибку в строке 46. Почему? Почему он не переводит с английской раскладки на русскую..???
0 |
|
17227 / 12679 / 3323 Регистрация: 17.09.2011 Сообщений: 20,950 |
|
|
13.01.2020, 15:08 |
2 |
|
Почему он не переводит с английской раскладки на русскую..? Потому что искомый символ отсутствует в словаре.
1 |
|
1 / 1 / 0 Регистрация: 19.04.2011 Сообщений: 22 |
|
|
13.01.2020, 15:11 [ТС] |
3 |
|
kolorotur, я пишу к примеру слово «Привет», если dictionary удалить то выводит «Ghbdtn», если оставить dictionary то выводит ошибку, но буквы то есть в словаре эти. p.s. спс, что обратил внимание на тему
0 |
|
17227 / 12679 / 3323 Регистрация: 17.09.2011 Сообщений: 20,950 |
|
|
13.01.2020, 15:20 |
4 |
|
я пишу к примеру слово «Привет» После чего поиск символов производите в словаре dictionary, который составлялся из символов строки En, в которой нет букв «П», «р», «и», «в», «е» и «т».
1 |
|
1 / 1 / 0 Регистрация: 19.04.2011 Сообщений: 22 |
|
|
13.01.2020, 15:23 [ТС] |
5 |
|
kolorotur, подскажешь как сделать так чтобы на выходе было соответствие русских букв английским? как исправить ситуацию эту?
0 |
|
798 / 581 / 207 Регистрация: 21.02.2019 Сообщений: 2,095 |
|
|
13.01.2020, 15:25 |
6 |
|
Nibros,
0 |
|
Nibros 1 / 1 / 0 Регистрация: 19.04.2011 Сообщений: 22 |
||||
|
13.01.2020, 15:39 [ТС] |
7 |
|||
|
carrotik, так у меня же идет сверка по словарю
1 элемент английской раскладки сопоставляется 1 элементу русской, что не так?
0 |
|
17227 / 12679 / 3323 Регистрация: 17.09.2011 Сообщений: 20,950 |
|
|
13.01.2020, 15:43 |
8 |
|
что не так? То, что вы проверяете русскую строку, а 1 элемент русской раскладки нигде не сопоставляется 1 элементу английской раскладки.
1 |
|
1 / 1 / 0 Регистрация: 19.04.2011 Сообщений: 22 |
|
|
13.01.2020, 15:45 [ТС] |
9 |
|
kolorotur, что надо дописать чтобы было сопостовление?
0 |
|
1008 / 626 / 213 Регистрация: 08.08.2014 Сообщений: 1,948 |
|
|
13.01.2020, 15:47 |
10 |
|
что надо дописать чтобы было сопостовление? Вам нужно два словаря, один En-Ru, второй Ru-En. И использовать один из них (или оба) в зависимости от условий задачи и входных данных.
1 |
|
17227 / 12679 / 3323 Регистрация: 17.09.2011 Сообщений: 20,950 |
|
|
13.01.2020, 15:48 |
11 |
|
что надо дописать чтобы было сопостовление? Товарищи carrotik и kotelok выше ответили:
составляйте второй словарь для обратной конвертации
Вам нужно два словаря, один En-Ru, второй Ru-En. Только после этого у вас возникнет еще одна проблема: определить, на каком языке введен текст и какой словарь использовать, что в текущем варианте мне видится невозможным без дополнительной информации от пользователя или из системы.
1 |
|
1 / 1 / 0 Регистрация: 19.04.2011 Сообщений: 22 |
|
|
13.01.2020, 15:51 [ТС] |
12 |
|
Понял, спасибо всем.
0 |
|
Kazbek17 1444 / 905 / 447 Регистрация: 06.02.2012 Сообщений: 2,780 |
||||
|
13.01.2020, 16:21 |
13 |
|||
|
Nibros, а что вам мешает сделать так.
0 |
|
17227 / 12679 / 3323 Регистрация: 17.09.2011 Сообщений: 20,950 |
|
|
13.01.2020, 16:44 |
14 |
|
Kazbek17, незеркальность данных.
0 |
|
5866 / 4743 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
|
|
13.01.2020, 16:58 |
15 |
|
незеркальность данных почему?
0 |
|
1123 / 794 / 219 Регистрация: 15.08.2010 Сообщений: 2,185 |
|
|
13.01.2020, 17:06 |
16 |
|
почему? чем должно стать
0 |
|
1 / 1 / 0 Регистрация: 19.04.2011 Сообщений: 22 |
|
|
13.01.2020, 17:08 [ТС] |
17 |
|
И все же, как будет выглядеть словарь обратной конвертации как писали выше? Или есть идеи как можно исправить ситуацию?
0 |
|
1444 / 905 / 447 Регистрация: 06.02.2012 Сообщений: 2,780 |
|
|
13.01.2020, 17:20 |
18 |
|
КОП, А кто говорил про множественный ввод данных? Речь идет о символьном реверсе.
0 |
|
5866 / 4743 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
|
|
13.01.2020, 17:27 |
19 |
|
Речь идет о символьном реверсе. Имеется в виду, что невозможно определить исходную раскладку при вводе символов, имеющихся в обоих алфавитах.
0 |
|
1123 / 794 / 219 Регистрация: 15.08.2010 Сообщений: 2,185 |
|
|
13.01.2020, 17:31 |
20 |
|
А кто говорил про множественный ввод данных? Речь идет о символьном реверсе. ну вот в моем примере 3 символа.
dictionary.Add(enen[i], ruru[i]); так вот чем станет точка в вашем варианте и почему?
0 |
An System.Collections.Generic.KeyNotFoundException “The given key was not present in the dictionary” can be the result of using a too old MySQL Connector/NET version in your ASP.NET web application. A KeyNotFoundException is thrown when an operation attempts to retrieve an element from a collection using a key that does not exist in that collection. An unsupported character set like utf8mb4 can be such a key, if your Connector/NET doesn’t support this character set. Luckily there is an easy workaround for this.
MySQL (Oracle) Connector/NET versions prior to 6.0.8, 6.1.6, 6.2.5, 6.3.6 lack a mapping for UTF8MB4 as charset. Connecting to a MySQL database and querying a table that has been created with CHARSET=utf8mb4 results in a .NET exception:
Exception Details: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at MySql.Data.MySqlClient.CharSetMap.GetCharacterSet(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.CharSetMap.GetEncoding(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.Driver.Configure(MySqlConnection connection) at MySql.Data.MySqlClient.MySqlConnection.Open() at ASP.mysql_data_aspx.MySQLConn()
A more extended exception is:
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at MySql.Data.MySqlClient.CharSetMap.GetCharacterSet(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.MySqlField.SetFieldEncoding() at MySql.Data.MySqlClient.NativeDriver.GetColumnData(MySqlField field) at MySql.Data.MySqlClient.NativeDriver.GetColumnsData(MySqlField[] columns) at MySql.Data.MySqlClient.Driver.GetColumns(Int32 count) at MySql.Data.MySqlClient.ResultSet.LoadColumns(Int32 numCols) at MySql.Data.MySqlClient.ResultSet..ctor(Driver d, Int32 statementId, Int32 numCols) at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId) at MySql.Data.MySqlClient.MySqlDataReader.NextResult() at MySql.Data.MySqlClient.MySqlDataReader.Close() at MySql.Data.MySqlClient.MySqlCommand.ResetReader() at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader() at ASP.mysql_data_aspx.MySQLConn()
Googling for a fix, some suggestions were to add CharSet=utf8; to your connection string. Unfortunately I was unable to resolve the exception with this added.
The best way to fix this System.Collections.Generic.KeyNotFoundException with Connector/NET is to simply update your Connector/NET version. Support for utf8mb4 charset is built in in versions 6.0.8, 6.1.6, 6.2.5, 6.3.6+:
MySQL Connector/NET did not support the
utf8mb4character set. When attempting to connect toutf8mb4tables or columns, an exceptionKeyNotFoundExceptionwas generated. (Bug #58244)https://dev.mysql.com/doc/relnotes/connector-net/en/news-6-0-8.html
And MySQL Connector/NET now supports MySQL servers configured to use utf8mb4 as the default character set in version 8.0.9.
MySQL Connector/NET now supports MySQL servers configured to use utf8mb4 as the default character set.
https://dev.mysql.com/doc/relnotes/connector-net/en/news-8-0-9.html
If, for some reason, you cannot or will not update your MySQL Connector/NET version anytime soon, there is an easy workaround available; SET NAMES 'utf8'. Yes, that’s right: as your first statement, set the three session system variables
- character_set_client
- character_set_connection
- character_set_results
to the given character set utf8. You can even use latin1, but that may give some undesired encoding issues…
Imaging the following C# MySql.Data.MySqlClient test script for querying your MySQL database table:
string sql = "select * from aspnet_site_comments";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) {
Response.Write(rdr[0]+ "<br/>");
}
rdr.Close();
}
catch (Exception ex) {
Response.Write(ex.ToString());
}Code language: C# (cs)
Are you looking for rock solid, eco-friendly, .NET hosting? Look no further! UmbHost offers powerful hosting services for websites and businesses of all sizes, and is powered by 100% renewable energy!
If your MySQL database server has in its my.cnf server config:
character_set_server utf8mb4
collation_server = utf8mb4_unicode_ciCode language: SQL (Structured Query Language) (sql)
And your table aspnet_site_comments is created using ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci, it throws an System.Collections.Generic.KeyNotFoundException exception. Alter your code to first set the character_set_* to utf8 (don’t mind my pseudo-code, you’ll get the idea) as a workaround for this issue:
string setcharset = "SET NAMES 'utf8'"; // <-- !!
MySqlCommand charsetcmd = new MySqlCommand(setcharset, conn);
MySqlDataReader charsetrdr = charsetcmd.ExecuteReader();
charsetrdr.Close()
string sql = "select * from aspnet_site_comments";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) {
Response.Write(rdr[0]+ "<br/>");
}
rdr.Close();
}
catch (Exception ex) {
Response.Write(ex.ToString());
}Code language: C# (cs)
Only use this as a temporary fix, you should still update Connector/NET ASAP. That’s it!
Protip: Donate $10, 20 or 30 through Paypal (or see my donate page) and support this site. Thank you <3
- Remove From My Forums
-
Общие обсуждения
-
Доброго времени суток!
При установке SQL Server 2012 в кластер. Возникает ошибка:
«Данный ключ отсутствует в словаре.«
Лог:
Службы компонента Database Engine
Status: Ошибка. Дополнительные сведения см. в журнале.
Reason for failure: Произошла ошибка во время процесса установки компонента.
Next Step: Устраните ошибку, пользуясь следующими сведениями, удалите компонент, а затем запустите
установку еще раз.
Component name: Экземпляры служб компонента SQL Server Database Engine
Component error code: 0x80131577
Error description: Данный ключ отсутствует в словаре.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server& EvtSrc=setup.rll&
EvtID=50000&ProdVer=11.0.2100.60&EvtType=0xD05BC945&EvtType=0xD05BC945-
Изменен тип
18 декабря 2013 г. 5:57
-
Изменен тип


