Entity framework 在给定foreignkey的EF中以编程方式使用导航属性
在我的项目中,我使用ADO.NET实现了EF。假设我在实体框架中有以下类Entity framework 在给定foreignkey的EF中以编程方式使用导航属性,entity-framework,reflection,navigation-properties,Entity Framework,Reflection,Navigation Properties,在我的项目中,我使用ADO.NET实现了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 Categor
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; }
}
然后我有了导航属性:
hasCategory:从CategoryId到ProductCategoryId,1到多
hasType:从TypeId到ProductTypeId,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,我想知道是否有任何方法可以获取匹配的导航属性hasCategory或hasType以获取名称。Oterhwise我不知道我应该在这两个类别和类型中寻找哪一个。可能会朝相反的方向尝试 附着的对象以友好方式接收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
}
然而,导航财产的名称仍然是私有的:
希望这有助于解决问题