I had some problems with this - my EntityKey has three properties (PK with 3 columns), and I did not want to check each of the columns because it would be ugly. I was thinking of a solution that works all the time with all entities.
Another reason for this is that I do not like to infect UpdateExceptions every time.
A little Reflection is required to get the key property values.
The code is implemented as an extension that simplifies the use of:
context.EntityExists<MyEntityType>(item);
Take a look:
public static bool EntityExists<T>(this ObjectContext context, T entity) where T : EntityObject { object value; var entityKeyValues = new List<KeyValuePair<string, object>>(); var objectSet = context.CreateObjectSet<T>().EntitySet; foreach (var member in objectSet.ElementType.KeyMembers) { var info = entity.GetType().GetProperty(member.Name); var tempValue = info.GetValue(entity, null); var pair = new KeyValuePair<string, object>(member.Name, tempValue); entityKeyValues.Add(pair); } var key = new EntityKey(objectSet.EntityContainer.Name + "." + objectSet.Name, entityKeyValues); if (context.TryGetObjectByKey(key, out value)) { return value != null; } return false; }
Sven Jan 14 '11 at 9:30 2011-01-14 09:30
source share