Search code examples
entity-frameworkentity-framework-4.1

How to get the Primary Key(s) in Entity Framework 4.1, i.e. using DbContext


The answers I'm seeing here are for ObjectContext. Is there a property to determine an entity's primary key names when using DbContext?

Ah.. one of those times that I wish Entity Framework is open source! I can glean this primary key name information from .Find method :-)


Solution

  • You cannot use DbContext for that - DbContext API is just dumb wrapper with only most needed functionality. For everything more complex you must convert DbContext back to ObjectContext and use it. Try something like this:

    Extract key names:

    public static string[] GetEntityKeyNames<TEntity>(this DbContext context) where TEntity : class
    {
      if (context == null)
        throw new ArgumentNullException("context");
    
      var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<TEntity>();
      var entitySet = set.EntitySet;
      return entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
    }
    

    Here's a method that will extract the key values of an entity:

    public static IEnumerable<object> GetEntityKeys<TEntity>(this DbContext context, TEntity entity)
      where TEntity : class
    {
      if (context == null)
        throw new NullReferenceException("context");
    
      var type = typeof(TEntity);
    
      var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<TEntity>();
      var entitySet = set.EntitySet;
      var keys = entitySet.ElementType.KeyMembers;
      var props = keys.Select(k => type.GetProperty(k.Name));
      return props.Select(p => p.GetValue(entity));
    }