efcore icon indicating copy to clipboard operation
efcore copied to clipboard

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key)

Open wilmanwar opened this issue 10 years ago • 2 comments

I did read the resolution for issue: #4031 but in my case it is slightly different condition that generates this KeyNotFound. Based on the GetIndexes() call that is done withing the SqlServerDatabaseModelFactory: the query: string str = "SELECT \r\n i.name AS [index_name],\r\n object_schema_name(i.object_id) AS [schema_name],\r\n object_name(i.object_id) AS [table_name],\r\n\ti.is_unique,\r\n c.name AS [column_name],\r\n i.type_desc\r\nFROM sys.indexes i\r\n inner join sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id\r\n inner join sys.columns c ON ic.object_id = c.object_id AND c.column_id = ic.column_id\r\nWHERE object_schema_name(i.object_id) <> 'sys' \r\n AND i.is_primary_key <> 1\r\n AND object_name(i.object_id) <> '__EFMigrationsHistory'\r\nORDER BY i.name, ic.key_ordinal";

is assuming that ordering by Index name is enough to get a grouping of all indexes by name. The problem is that although a Table cannot have two different indexes named the same, two different tables in sql can have the same exact name to their own index. This causes the while loop on the datareader to incorrectly assume that if the current row for the index has the same name then we are still in the same Table Model when in fact we are not.

This can be fixed by changing the ORDER BY to include the table name first like so: ... ORDER BY object_name(i.object_id), i.name, ic.key_ordinal

then when the while loop runs it will correctly switch the table models and not generate this error.

wilmanwar avatar Feb 15 '16 18:02 wilmanwar

This was fixed a while back (before the big rename). The current code reads:

ORDER BY object_schema_name(i.object_id), object_name(i.object_id), i.name, ic.key_ordinal

see here. RC2 will contain this fix.

lajones avatar Feb 16 '16 17:02 lajones

I see the fix thanks. I'll test again when RC2 comes out.

wilmanwar avatar Feb 17 '16 20:02 wilmanwar