Friday 6 November 2009

EF: Extension method for fetching entities by their ID

Here's a handy extension method which lets you get an entity from an object context given the entity's ID:

public static T GetEntityById(this ObjectContext context, int id)
{
EntityType type = (from meta in context.MetadataWorkspace.GetItems(DataSpace.CSpace)
where meta.BuiltInTypeKind == BuiltInTypeKind.EntityType
select meta)
.OfType()
.Where(e => e.Name == typeof(T).Name).Single();

EntityKey key = new EntityKey(context.GetType().Name + "." + typeof(T).Name, "Id", id);

return (T)context.GetObjectByKey(key);
}