views:

603

answers:

3

Hi

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

A: 

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?

J.W.
A: 

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

Timothy Walters
+2  A: 
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.

Shimmy