6

我有一个配置了以下实体的实体框架代码优先 DbContext。在这个例子中,类 Bar 是类 Foo 的子类。

public class Foo
{
    public Guid Id { get; set; }

    public virtual ICollection<Bar> Bars { get; set; }
}

public class Bar
{
    public Guid Id { get; set; }

    public Guid FooId { get; set; }

    public virtual Foo Foo { get; set; }
}

现在我知道,在内部,Entity Framework 理解 Foo 和 Bar 之间的关系是由外键 Bar.FooId 定义的。我想做的是在运行时使用表达式以某种方式提取这种关系。我想实现一个行为如下的方法:

var context = new FooBarDbContext();
var bar = context.Set<Bar>().First();

// I want this method to return bar.FooId when passed the expression b => b.Foo
object result = MyService.GetForeignKeyValue(bar, b => b.Foo); 

现在在这个简单的例子中,我知道我可以得到 bar.FooId 并完成。关键是我正在编写一个类,我相信上面指定的 GetForeignKeyValue 方法对用户来说是最干净的接口。

是否可以查询 DbContext 配置以确定哪个属性用作导航属性的外键?(假设有一个)

4

2 回答 2

7

通过使用NavigationProperty类的GetDependentProperties方法,我实际上能够确定外键属性。

这是我用来(或多或少)获得所需内容的代码:

object[] GetForeignKeyPropertyValues<TEntity, TRelatedEntity>(TEntity entity, Expression<Func<TEntity, TRelatedEntity>> navigationProperty)
{
    if (entity == null)
        return new object[] { };

    // Find the entity metadata in the object context.
    // (Assume you have access to the DbContext through the property CurrentDbContext.)
    var objectContext = (CurrentDbContext as IObjectContextAdapter).ObjectContext; 

    var metadataNamespace = ObjectContextAdapter.GetType().Namespace;

    var entityIdentity = metadataNamespace + "." + typeof(TEntity).Name; // HACK: This seems to work to retrieve the EntityType for an entity.
    var entityMetadata = objectContext.MetadataWorkspace.GetItem<EntityType>(entityIdentity, DataSpace.CSpace);

    // TODO: Verify that the entity metadata was found.

    // Get the navigation property metadata by parsing the name from the navigation property expression.
    var navigationPropertyName = GetPropertyName(navigationProperty);
    var navigationPropertyMetadata = entityMetadata.NavigationProperties.FirstOrDefault(np => np.Name == navigationPropertyName);

    // TODO: (JMB) Verify that the navigation property metadata was found.

    // Extract the foreign key columns from the navigation property.
    var foreignKeyPropertyMetadatas = navigationPropertyMetadata.GetDependentProperties();

    // Create property getters for each foreign key property.
    var foreignKeyPropertyGetters = foreignKeyPropertyMetadatas
        .Select(propertyMetadata => MakePropertyGetter<TEntity>(propertyMetadata.Name))
        .ToArray();

    // Execute the foreign key property getters to get the foreign key property values for the specified entity.
    var foreignKeyPropertyValues = foreignKeyPropertyGetters
        .Select(propertyGetter => propertyGetter(entity))
        .ToArray();

    return foreignKeyPropertyValues;
}

static string GetPropertyName<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> navigationProperty)
{
    var lambda = navigationProperty as LambdaExpression;
    var member = lambda.Body as MemberExpression;

    return member.Member.Name;
}

static Func<TEntity, object> MakePropertyGetter<TEntity>(Type entityType, string propertyName)
{
    var parameterExpression = Expression.Parameter(typeof(TEntity), "entity");
    var propertyExpression = Expression.PropertyOrField(parameterExpression, propertyName);

    var lambdaExpression = Expression.Lambda(propertyExpression, parameterExpression);
    var lambdaFunction = lambdaExpression.Compile();

    return (Func<TEntity, object>)lambdaFunction;
}
于 2013-10-25T14:30:02.960 回答
-3

EF 知道 FooID 是 Foo 对象属性的外键属性的默认方式是基于命名约定- 有什么理由不能依赖相同的假设?如果是这样,只需获取您的表达式参数表示的字符串,附加“Id”,就可以了。

如果您没有遵循命名约定并且没有在模型上使用属性,我认为您不走运。没有记录从 DbContext 获取DbModelBuilder引用的方法(至少我找不到)。

于 2013-10-23T21:44:00.183 回答