Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Get object by ID?

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?

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

like image 633
James P. Wright Avatar asked May 27 '11 18:05

James P. Wright


2 Answers

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.

like image 120
Ladislav Mrnka Avatar answered Sep 20 '22 06:09

Ladislav Mrnka


I think the Find() method may be able to do what you're looking for (DbSet.Find Method).

var someEntity = dbSet.Find(keyValue); 
like image 22
Yuck Avatar answered Sep 20 '22 06:09

Yuck