Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

Loading Entities Dynamically with Entity Framework

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

Comments

Ramon Smits said:

Dude,

Why not just use the Set<T> method on the context? Much easier and actually access to the Find(..) method.

I use that all the time as IDbSet<T> is 'the' interface to use in EF dynamic scenarios.

# December 14, 2012 5:05 PM

RichardD said:

It's much simpler with a DbContext:

public static object Load(this DbContext ctx, Type type, params object[] ids)

{

   return ctx.Set(type).Find(ids);

}

public static T Load<T>(this DbContext ctx, params object[] ids)

{

   return ctx.Set<T>().Find(ids);

}

# December 17, 2012 11:34 AM

Ricardo Peres said:

@RichardD:

Yes, I know... but this is with ObjectContext.

# December 17, 2012 12:09 PM

Ricardo Peres said:

Ramon:

Did you not understand my post? I don't have a "T", I only have a "Type"... :-)

# February 2, 2013 5:00 AM