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 sing开发者_运维问答le 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?
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();
}
精彩评论