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?
}
}
Yes you can. If you know that all your entities will have simple primary key property of type
intand nameIdyou can do simply this:All your entities must implement this interface. Next you can simply do:
This is the simplest possible solution. There are better solutions using
GetObjectByKeybut they are more complex. The difference betweenFirstOrDefaultandGetObjectByKeyis repeatable execution.FirstOrDefaultalways executes DB query whereasGetObjectByKeyfirst 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 usingGetObjectByKeyyou 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: