【问题标题】:Programmatically use navigation properties in EF given the foreignkey给定外键,以编程方式在 EF 中使用导航属性
【发布时间】:2013-01-11 17:12:30
【问题描述】:

在我的项目中,我有 EF with ADO.NET。假设我在Entity Framework 中有以下类

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:从 Category(Id) 到 Product(CategoryId),从 ​​1 到 Many
  2. hasType:从 Type(Id) 到 Product(TypeId),从 ​​1 到 Many

因此,如果我想访问产品的特定类别名称或类型名称(给定上下文):

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 两个类中寻找哪个。

【问题讨论】:

    标签: entity-framework reflection navigation-properties


    【解决方案1】:

    也许尝试相反的方向?

    附加对象动态接收“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
    }
    

    尽管如此,导航属性的名称仍然是私有的 :( 希望这能找到解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 2016-01-09
      • 2021-11-10
      相关资源
      最近更新 更多