runxc1 Bret Ferrier
runxc1 Bret Ferrier

Reputation: 8233

Entity Framework 4 load Record by ID

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?

Upvotes: 3

Views: 1603

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

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();
}

Upvotes: 2

Related Questions