0

I'd like to know how to create a method that will allow me to generically do this...

public class Repo<T> : IGenericRepo<T> where T : class
    {
        protected PteDotNetEntities db;

        public T Get(int id)
        {
            //how do I dynamically get to the correct entity object and select it by
            //id?
        }

    }
Exitos
  • 29,230
  • 38
  • 123
  • 178

1 Answers1

0

Yes you can. If you know that all your entities will have simple primary key property of type int and name Id you can do simply this:

public interface IEntity
{
    int Id { get; }
}

All your entities must implement this interface. Next you can simply do:

public class Repo<T> : IGenericRepo<T> where T : class, IEntity
{
    protected PteDotNetEntities db;

    public T Get(int id)
    {
        return db.CreateObjectSet<T>().FirstOrDefault(e => e.Id == id);
    }
}

This is the simplest possible solution. There are better solutions using GetObjectByKey but they are more complex. The difference between FirstOrDefault and GetObjectByKey is repeatable execution. FirstOrDefault always executes DB query whereas GetObjectByKey first checks if the entity with the same key was already loaded / attached to the context and returns it without querying the database. As reference for version using GetObjectByKey you can check similar questions:

You can simplify those examples if you know the name of the key property upfront (forced by the interface).

In case of using code first / DbContext API you can also check this question:

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670