views:

140

answers:

1

So I am looking at creating a generic Interface to interact with my DataStorage of my objects one that I can swap out to use EF4 or SubSonic or NHibernate or some NoSQL option.

So I have an ERD and every table has an auto incrementing int column "TableNameID" that is the primary key I am trying to figure out how to get a single record from the DB using the primary key in a Generic method

public T GetSingle<T>(int primaryKey) where T : class

How do you do this using EF4?

+1  A: 

You could do this via the generic ObjectContext.CreateObjectSet().

E.g., something like:

public T GetSingle<T>(int primaryKey) where T : class
{
    var q = Context.CreateObjectSet<T>().Where("it.TableNameID = @tableNameId");
    q.Parameters.Add(new ObjectParameter("tableNameId", primaryKey));
    return q.Single();
}
Craig Stuntz
I guess I should have been more clear if the Table's name is Users the Primary Key is UsersID. I think this is a start but I guess it would work best if I can find the name of the Primary Key somehow via EF4
runxc1 Bret Ferrier
This looks like it is the best answer I can find along with using reflection to find the class name and have the class name the same as the table name and all IDs follow a standard.
runxc1 Bret Ferrier
You don't need reflection to get the class name. `typeof(T).Name` will do, and doesn't require `System.Reflection`
Craig Stuntz
I asked another related question. And posted the answer there which works better than the one here http://stackoverflow.com/questions/2958921/entity-framework-4-how-to-find-the-primary-key
runxc1 Bret Ferrier
You said you were trying to avoid reflection? Changed your mind on that?
Craig Stuntz