Do you want a general way to check if an object has been loaded in a context or in a general way to query a database if an entity exists?
In the first case, use:
public bool Exists<T>(T entity) { return this.Set<T>().Local.Any(e => e == entity); }
In the latter case, use (it will also check the loaded objects):
public bool Exists<T>(params object[] keys) { return (this.Set<T>().Find(keys) != null); }
Edit:
The EF code should not first access this information, but you can get the name of the entity. I think something like this should work:
var objContext = ((IObjectContextAdapter)dbContext).ObjectContext; var objSet = objContext.CreateObjectSet<T>(); var keyNames = objSet.EntitySet.ElementType.KeyMembers.Select(m => m.Name);
But all this does not make sense. You want to use a general approach, but your entities do not provide the necessary information to provide a general approach. Now you say that you donโt even know the key meanings. Using this โgeneralโ approach will require reflection and manual construction of the expression tree.
Ladislav Mrnka May 16 '11 at 14:59 2011-05-16 14:59
source share