2013-01-11 17 views
1

在我的項目中我有EF with ADO.NET。假設我有Entity Framework以下類以編程方式使用EF中的導航屬性給定​​外鍵

class Product 
{ 
    int Id { get; set;} 
    string Name { get; set; } 
    int TypeId { get; set; } 
    int CategoryId { get; set; } 
} 

class Type 
{ 
    int Id { get; set; } 
    string Name { get; set; } 
} 

class Category 
{ 
    int Id { get; set; } 
    string Name { get; set; } 
} 

然後,我有navigation properties

  1. hasCategory:從類別(Id)的產品(類別ID),1對多
  2. hasType:從類型(Id)到產品(TypeId),1到許多

因此,如果我要訪問一個特定的類別名稱或產品的類型名稱(給出的上下文中):如果我有屬性的名稱,我可以得到的財產

int productId = 1; 
var categoryName = context.Products.Single(p => p.Id == productId).hasCategory.Name; 
var typeName = context.Products.Single(p => p.Id == productId).hasType.Name; 

現在:

string propertyName = "CategoryId"; 
var propertyValue = GetType(Product).GetProperty(propertyName) 

鑑於propertyName我想知道是否有任何方法獲得匹配的導航屬性(hasCategoryhasType)以獲取名稱。在我看來,我不知道兩個類別CategoryType中的哪一個。

回答

0

也許嘗試在相反的方向?

附加對象可以通過「RelationshipManager」屬性進行消息傳遞。它提供了一個有用的方法GetAllRelatedEnds(),它返回一個「RelatedEnd」集合,您可以在其中找到例如關係名稱。

Object myObj; 
var q = myObj.GetType().GetProperties().Where(p => p.PropertyType == typeof(RelationshipManager)).First(); 
RelationshipManager rm = q.GetValue(myObj, null) as RelationshipManager; 
foreach (RelatedEnd re in rm.GetAllRelatedEnds()) 
{ 
    // Here you get the "other-side" objects 
} 

儘管如此,導航屬性的名稱保持私人:( 希望這個方法有人解決