title: Entity Framework Code First: How can I determine the foreign key property used for a navigation property at runtime?
body: <p>I have an Entity Framework Code First DbContext with the following entities configured. In this example class Bar is a child of class Foo.</p>
  
  <pre><code>public class Foo
  {
      public Guid Id { get; set; }
  
      public virtual ICollection&lt;Bar&gt; Bars { get; set; }
  }
  
  public class Bar
  {
      public Guid Id { get; set; }
  
      public Guid FooId { get; set; }
  
      public virtual Foo Foo { get; set; }
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>var context = new FooBarDbContext();
  var bar = context.Set&lt;Bar&gt;().First();
  
  // I want this method to return bar.FooId when passed the expression b =&gt; b.Foo
  object result = MyService.GetForeignKeyValue(bar, b =&gt; b.Foo); 
  </code></pre>
  
  <p>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.</p>
  
  <p><strong>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)</strong></p>