Entity Framework v2: How to get only one entity easier with EF4
Alex James wrote an extension method which allows to get only one entity from a query and the entity key.
If we have the key, I think it’s useless to allow it for all queries and it’s useful only for EntitySet. With EF4, this extension method can be applied on ObjectSet class instead of ObjectQuery class.
// In the first version of Entity Framework, the ObjectSet class doesn’t exist, EntitySet were some ObjectQuery.
// ObjectSet<T> class inherits from ObjectQuery<T>
This simplifies the code because we can directly use the (Try)GetObjectByKey method:
public static class ObjectSetExtension
{
public static T Get<T>(this ObjectSet<T> objectSet, object key) where T : class
{
object value;
objectSet.Context.TryGetObjectByKey(new EntityKey(string.Concat(objectSet.Context.DefaultContainerName, ".", objectSet.EntitySet.Name), objectSet.EntitySet.ElementType.KeyMembers.Single().Name, key), out value);
return (T)value;
}
public static T Get<T>(this ObjectSet<T> objectSet, params EntityKeyMember[] keys) where T : class
{
object value;
objectSet.Context.TryGetObjectByKey(new EntityKey(string.Concat(objectSet.Context.DefaultContainerName, ".", objectSet.EntitySet.Name), keys), out value);
return (T)value;
}
}
We can use the second extension method for entities with composite key.