Loading Entities Dynamically with Entity Framework

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Fri, 14 Dec 2012 15:24:37 GMT Indexed on 2012/12/14 17:04 UTC
Read the original article Hit count: 217

Filed under:
|
|

Sometimes we may be faced with the need to load entities dynamically, that is, knowing their Type and the value(s) for the property(ies) representing the primary key.

One way to achieve this is by using the following extension methods for ObjectContext (which can be obtained from a DbContext, of course):

   1: public static class ObjectContextExtensions
   2: {
   3:     public static Object Load(this ObjectContext ctx, Type type, params Object [] ids)
   4:     {
   5:         Object p = null;
   6:  
   7:         EntityType ospaceType = ctx.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).SingleOrDefault(x => x.FullName == type.FullName);
   8:  
   9:         List<String> idProperties = ospaceType.KeyMembers.Select(k => k.Name).ToList();
  10:  
  11:         List<EntityKeyMember> members = new List<EntityKeyMember>();
  12:  
  13:         EntitySetBase collection = ctx.MetadataWorkspace.GetEntityContainer(ctx.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.Where(x => x.ElementType.FullName == type.FullName).Single();
  14:  
  15:         for (Int32 i = 0; i < ids.Length; ++i)
  16:         {
  17:             members.Add(new EntityKeyMember(idProperties[i], ids[i]));
  18:         }
  19:  
  20:         EntityKey key = new EntityKey(String.Concat(ctx.DefaultContainerName, ".", collection.Name), members);
  21:  
  22:         if (ctx.TryGetObjectByKey(key, out p) == true)
  23:         {
  24:             return (p);
  25:         }
  26:  
  27:         return (p);
  28:     }
  29:  
  30:     public static T Load<T>(this ObjectContext ctx, params Object[] ids)
  31:     {
  32:         return ((T)Load(ctx, typeof(T), ids));
  33:     }
  34: }

This will work with both single-property primary keys or with multiple, but you will have to supply each of the corresponding values in the appropriate order.

Hope you find this useful! Winking smile

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about .NET 4