2009-07-03 31 views

回答

3

如果你能得到的EntitySet的,或者的EntityType,爲實體,那麼你可以使用KeyMembers屬性:

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 
} 

您可以從上下文設置一個通用對象:

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

實體類仍然是一個從System.Data.Objects.DataClasses.EntityObject繼承的類,所以,我認爲反射仍然會對它起作用。

你試過了嗎?你有什麼錯誤嗎?

1

此實體框架支持論壇中的post顯示瞭如何使用反射來查找ID字段及其詳細信息。

5
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; 
} 

您可以將兩個funcs合併爲一個或設置您的搜索條件。

相關問題