I have an Entity Framework Code First DbContext with the following entities configured. In this example class Bar is a child of class 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; }
}
Now I know that internally, Entity Framework understands that the relationship between Foo and Bar is defined by the foreign key Bar.FooId. What I'd like to do is to somehow extract that relationship at runtime using expressions. I'd like to implement a method that behaves as follows:
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);
Now in this simplistic example I know that I could just get bar.FooId and be done. The point is that I'm writing a class for which I believe the GetForeignKeyValue method specified above is the cleanest interface for a user.
Is it possible to query the DbContext configuration to determine which property is used as the foreign key for a navigation property? (Assuming there is one)