title: One to Many in Code First Entity Framework model - How do the relationships work?
body: <p>Given the standard Northwind database (reduced for conciseness):</p>
  
  <pre><code>   [Table("Order Details")]
      public class OrderDetail : IValidatableObject
      {
          [Key, Column(Order = 1)]
          public int OrderID { get; set; }
          [Key, Column(Order = 2)]
          public int ProductID { get; set; }
          ...
      }
     [Table("Orders")]
      public class Order
          {
          public int OrderID { get; set; }
          ...
          public virtual ICollection&lt;OrderDetail&gt; OrderDetails { get; set; }
      }
  </code></pre>
  
  <p>I'm wondering about how this works exactly.  I'm guessing that because the primary key in Order (OrderID) has foreign key in OrderDetails (OrderID) that is named the same, EF's rules correctly guess that they have a foreign-key/primary key relationship.</p>
  
  <p>Is that correct?</p>
  
  <p>Part two is another question:</p>
  
  <p>I have an existing database where the foreign key is not named the same (change OrderId in OrderDetail to RecordNumber, for example - (I can't change the database)). In this  case, I'm struggling trying to understand how to relate the two tables.  </p>
  
  <p>I'm using the Fluent API (and not the annotations as in above) and have something like this:</p>
  
  <pre><code>---OrderDetails
  
  // set up the primary key
  HasKey(t =&gt; new { t.RecordNumber, t.ProductID };
  
  ---Order
  
  HasKey(t =&gt; t.OrderId);
  
  HasRequired(t =&gt; t.OrderDetails).WithMany().HasForeignKey(t =&gt; t.OrderId)
  </code></pre>
  
  <p>(The last statement seems incredibly wrong, in that the only thing that HasForeignKey(...) seems to be able to relate to is the declared primary composite key)</p>
  
  <p>I've also tried</p>
  
  <pre><code>HasMany((t =&gt; t.OrderDetails).WithMany()
  </code></pre>
  
  <p>which would seem to be different from the prior statement in that it makes it possible to have no OrderDetails.</p>
  
  <p>Neither works.</p>
  
  <p>The idea I am trying to express is that an order must have at least one OrderDetails - and I'm trying to be able to navigate thusly:  </p>
  
  <pre><code>   Con.Orders.Single(o =&gt; o.OrderId == 1).OrderDetails
  </code></pre>
  
  <p>The problem I am having is that the foreign key I declared with HasForeignKey(...) does not relates to anything on Orders (and the code throws an appropriate exception - "Multiplicity is not valid"), and I am left not knowing how to accomplish my goal.  </p>
  
  <p>Any thoughts?  I appreciate your help in advance.</p>