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

佐手、 提交于 2019-12-04 18:54:15

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>();
}
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 &&
                       ((EdmScalarPropertyAttribute)a).EntityKeyProperty
                     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.
                  Trim())).FirstOrDefault();
    if (string.IsNullOrEmpty(id)) id = ids.First();
    return id;
}

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

This post in the Entity Framework support forums shows how to use reflection to find ID fields and their details.

Entity class is still a class which inherits from System.Data.Objects.DataClasses.EntityObject, so, i think reflection will still work on it.

Have you tried it? Do you get any error?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!