Skip to content

KeyNotFoundException: The given key 'Id' was not present in the dictionary. #79

@LucasWBritz

Description

@LucasWBritz

Hi!
I'm getting this error randomly when I try to query data from our database using dapper and then convert the result to an object using Slapper.

Code sample:

var data = await _dapperRepository.QueryAsync<dynamic>(sqlQuery, parameters);
var result = Slapper.AutoMapper.MapDynamic<UserData>(data).ToList();
The exception:
System.Collections.Generic.KeyNotFoundException: The given key 'Id' was not present in the dictionary.   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)   at System.Linq.Enumerable.SelectListIterator`2.ToArray()   at System.Linq.Enumerable.DefaultIfEmptyIterator`1.ToArray()   at Slapper.AutoMapper.InternalHelpers.GetCacheKey(Type type, IDictionary`2 properties, Object parentInstance)   at Slapper.AutoMapper.InternalHelpers.GetInstance(Type type, IDictionary`2 properties, Object parentInstance)   at Slapper.AutoMapper.InternalHelpers.MapCollection(Type type, IDictionary`2 dictionary, Object instance, Object parentInstance)   at Slapper.AutoMapper.InternalHelpers.Map(IDictionary`2 dictionary, Object instance, Object parentInstance)   at Slapper.AutoMapper.Map(Type type, IEnumerable`1 listOfProperties, Boolean keepCache)   at Slapper.AutoMapper.MapDynamic[T](IEnumerable`1 dynamicListOfProperties, Boolean keepCache) 

This error is happening inside this method when trying to Select(id => properties[id]). The Key does not exist in the dictionary and is throwing this exception.

private static InstanceKey GetCacheKey(Type type, IDictionary<string, object> properties, object parentInstance)
  {
        var identifierValues = GetIdentifiers(type)?.Select(id => properties[id]).DefaultIfEmpty(Guid.NewGuid()).ToArray()
         ?? new object[] { Guid.NewGuid() };

         var key = new InstanceKey(type, identifierValues, parentInstance);
         return key;
  }

Unfortunately I'm not able to reproduce the error locally and submit a pull request because it happens randomly in our production environment. Never had this issue running locally and debugging.

Does anyone have an idea on what could be the cause of the error?

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions