Is there a method to acquire the name of the entity id-field using reflection or something?

.net c# entity-framework propertyinfo reflection


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

7/3/2009 2:17:41 AM

Accepted Answer

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>();
2/28/2011 1:56:42 PM

Popular Answer

public static IEnumerable<string> GetIdFields<TEntity>() where TEntity
  : EntityObject
    var ids = from p in typeof(TEntity).GetProperties()
              where (from a in p.GetCustomAttributes(false)
                     where a is EdmScalarPropertyAttribute &&
                     select true).FirstOrDefault()
              select p.Name;
    return ids;

public static string GetIdField<TEntity>() where TEntity : EntityObject
    IEnumerable<string> ids = GetIdFields<TEntity>();
    string id = ids.Where(s => s.Trim().StartsWith(typeof(TEntity).Name.
    if (string.IsNullOrEmpty(id)) id = ids.First();
    return id;

You could merge both funcs into one or set your search conditions.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow