I am trying to implement caching mechanism for entities. And to use the entities correctly and seamlessly with the caching i need to detach the entity from the current conte
IEntityWithKey is interface for other types of entities. It is for "big" entities. For example EntityObject implement this interface. These entities are not considered as POCO and are not supported by DbContext API.
If you want to use IEntityWithKey your classes must implement it - it is not something that would happen automatically.
Correct attaching with DbContext API should be:
dbContext.Set(typeof(entity)).Attach(entity);
and this should hopefully also work:
dbContext.Entry(entity).State = EntityState.Unchanged;
Correct detaching with DbContext API should be:
dbContext.Entry(entity).State = EntityState.Detached;
Also it is better to you generic methods instead of object.