Note that if change tracking is disabled on your context, asking the ObjectStateManager
or the ChangeTracker
might return that the object is not in the ObjectContext
even if it is in fact already in there. Therefore, if you try to attach such object it will raise an exception.
context.Set<T>().Local.Any(e => e.Id == id);
works event if change tracking is disabled.
if you do not know the type of the object, there is various approach, either you define a method using reflection or other techniques like this one
int GetIdOf(object entity){...}
Or you define an interface used by your classes like
public interface IMyEntity
{
int Id{get;set;}
}
and use it this way :
context.Set(e.GetType()).Local.Cast<IMyEntity>().Any(e => e.Id == id);