EF4 Generic Search by ID
I have x number of tables and all tables have a uniqueidentifier/guid primary key. I want to write a generic function that will take a Guid param id where T is EntityObject like so...
public T SelectById<T>(Guid id) where T : EntityObject
It seems like this would be a simple thing to do. I've 开发者_JAVA百科scoured the internet and can't quite find a way to do it, much less an elegant way. What am I missing here, why is this difficult?
In order to implement this you would to make sure your the ID properties on your Entities conform to a naming convention, something like Id or EntityName_Id. Then all you have to do is build up the EntityKey using a little bit of Reflection.
ObjectStateEntry entry;
var entityKey = new EntityKey(Context.DefaultContainerName + "." + typeof(T).Name, "Id", id);
object entity = null;
if (!Context.ObjectStateManager.TryGetObjectStateEntry(entityKey, out entry) || entry.Entity == null)
{
try
{
entity = Context.GetObjectByKey(entityKey);
}
catch (ObjectNotFoundException)
{
}
}
return (T)entity;
精彩评论