Search code examples
c#.netentity-frameworkreflectionpropertyinfo

Is there a way to get entity id-field's name by reflection or whatever?


I am trying to get the ID field name (property name) of an entity, is it possible?

User user= new User(); //User is an Entity

string idField = ??????? //user.UserId


Solution

  • If you can get the EntitySet, or the EntityType, for the entity, then you can use the KeyMembers property:

    public IEnumerable<string> GetIdProperties(EntitySetBase entitySet)
    {
      return GetIdProperties(entitySet.ElementType);
    }
    
    public IEnumerable<string> GetIdProperties(EntityTypeBase entityType)
    {
      return from keyMember in entityType.KeyMembers
             select keyMember.Name
    }
    

    You can obtain a generic object set from the context:

    public ObjectSet<TEntity> GetEntitySet<TEntity>(ObjectContext context)
    {
        return context.CreateObjectSet<TEntity>();
    }