System.InvalidCastException: Unable to cast object of type 'ApplicationDbContext' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'

214 views Asked by At

I recently upgraded my app to .net core 6 and now I am getting this error in line this code:

public List<KeyValuePair<string, long>> GetKeys(EntityEntry entry)
{
    var keys = new List<KeyValuePair<string, long>>();
    var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);

    if (objectStateEntry.EntityKey.EntityKeyValues != null)
    {
        keys.AddRange(objectStateEntry.EntityKey.EntityKeyValues.Select(key => new KeyValuePair<string, long>(key.Key, Convert.ToInt64(key.Value))));
    }

    return keys;
}

The value this refers to ApplicationDbContext

UPDATE

I was able to get the keyName but not sure how to get the keyValue

var keyName = entry.CurrentValues.EntityType.FindPrimaryKey().Properties
       .Select(x => x.Name).Single();
0

There are 0 answers