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

后端 未结 5 1898
逝去的感伤
逝去的感伤 2020-12-29 08:52

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 tha

5条回答
  •  Happy的楠姐
    2020-12-29 09:42

    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(this DbContext context) where TEntity : class
    {
      if (context == null)
        throw new ArgumentNullException("context");
    
      var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet();
      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 GetEntityKeys(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();
      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));
    }
    
        

    提交回复
    热议问题