EntityFramework How can I get an item by ID?

asp.net c# entity-framework linq reflection


Is it possible with Generics to get an object from my EntityFramework without knowing the type?

I'm thinking of something along the lines of:

public T GetObjectByID<T>(int id)
   return (from i in myDatabase.T where i.ID == id select i);

Is that doable? Could I use Reflection to somehow take T.GetType().Name and use that for the table?

Another hangup, is that not all tables available to me use "ID" as their unique column name.

5/27/2011 8:18:36 PM

Accepted Answer

Finally solved the issue with this:

To call the code I use this:

// Get the id of the object we are saving
PropertyInfo prop = GetProperty<TEntity>(entity, entity.EntityKey.EntityKeyValues[0].Key);
string entityID = prop.GetValue(entity, null).ToString();

// Get the current version of this object
var originalEntity = GetEntity<TEntity>(PropertyEquals, entityID);

This makes the assumption that the Primary Key you are searching on is the first one in the list of Primary Keys.

5/28/2011 2:05:30 AM

Popular Answer

You can define interface implemented by all your entities:

public interface IEntity
    int Id { get; }

and method to retrieve your entity:

public T GetObjectById<T>(int id) where T : class, IEntity
    return context.CreateObjectSet<T>().SingleOrDefault(e => e.Id == id);

You can also use similar approach to one provided in the linked question. You just have to use another method to get your entity:

public virtual T GetByKey<T>(int id) where T : class, IEntity
     string containerName = context.DefaultContainerName;
     string setName = context.CreateObjectSet<T>().EntitySet.Name;
     // Build entity key
     var entityKey = new EntityKey(containerName + "." + setName, "Id", id);
     return (TEntity)Context.GetObjectByKey(entityKey);         

The difference is that first method always query the database even if you have already loaded the instance to the context whereas second approach first checks if the instance is already loaded. The method is not so efficient because it builds these names over and over. Here is more general approach which can work with any key type and name and here is approach working with complex keys.

Neither of this method directly works with inheritance - you must provide base type to make it work.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow