EntityFramework How can I get an item by ID?

asp.net c# entity-framework linq reflection


Can I get an item from my EntityFramework using Generics without knowing its type?

Something along these lines comes to mind:

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

That's possible? Could I do some action using reflection?T.GetType().Name and use it as the table?

Another issue is that not all of the tables I have access to utilize "ID" as the name of their distinctive field.

5/27/2011 8:18:36 PM

Accepted Answer

This finally provided a solution:

I use this to invoke the code:

// 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 presupposes that the Primary Key you are looking on is the first Primary Key shown.

5/28/2011 2:05:30 AM

Popular Answer

You may specify the interface that each of your things must implement:

public interface IEntity
    int Id { get; }

and a way to get your entity back:

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

You may also use a strategy similar to the one described in the related query. Simply utilize a different approach to get your object.

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 first technique always queries the database, regardless of whether you have loaded the instance into the context, while the second approach first determines if the instance has been loaded. Because these names are created repeatedly, the process is not very effective. The approaches Here and here both work with complicated keys, however the former is more all-encompassing and may be used with any key type and name.

This method does not directly interact with inheritance; in order for it to function, a base type must be provided.

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