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.

This entry was posted in 7671, 7674. Bookmark the permalink.

3 Responses to Entity Framework v2: How to get only one entity easier with EF4

  1. Alex James says:

    Nice post Matthieu.

    I was thinking of doing something like this myself, but I had an ulterior motive too, I wanted to show how to build the query manually in eSQL.

    Anyway, nice one.

    Alex

  2. Jonathan A says:

    Exactly what I was looking for. Thanks !

  3. Vincent says:

    USed it, liked it

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>