title: Entity Framework Code First Foreign Key Problems
body: <p>I am trying to use EF Code First on an existing database. I first tried some of the reverse-engineering tools, but I ran into problems with that, so at the moment I am trying to hand-code some of the classes. I am having some trouble getting some of the foreign key relationships set up. Consider two tables. The first is called LocaleValueLookup:</p>
  
  <pre><code>public class LocaleValueLookup
  {
      public int Id { get; set; }
      public Guid Guid { get; set; }
  }
  </code></pre>
  
  <p>This table provides an Id for multi-language text held in a different table (that other table is not important for the purposes of this question). The second table is called SectionType, and it has an optional FK to LocaleValueLookup:</p>
  
  <pre><code>public class SectionType
  {
      public int EnumId { get; set; }
      public string Name { get; set; }
      public int? DefaultSectionTextLocaleValueLookupId { get; set; }
  
      // Navigation property
      public LocaleValueLookup DefaultSectionTextLocaleValueLookup { get; set; }
  }
  </code></pre>
  
  <p>I have tried various things, including adding a [ForeignKey] attribute to the SectionType.LocaleValueLookup property, and various incantations in the DbContext.OnModelCreating() override, but <strong>when I query the DbContext, I can't get the DefaultSectionTextLocaleValueLookup to be anything but null.</strong> I can retrieve other objects from the context just fine, and I have verified that DefaultSectionTextLocaleValueLookupId is not null at least some of the time.</p>
  
  <p>My OnModelBuilding() contains the following:</p>
  
  <pre><code>modelBuilder.Entity&lt;LocaleValueLookup&gt;()
      .ToTable("LocaleValueLookup")
      .HasKey(lvl =&gt; lvl.Id);
  modelBuilder.Entity&lt;LocaleValueLookup&gt;().Property(lvl =&gt; lvl.Id).IsRequired();
  
  modelBuilder.Entity&lt;SectionType&gt;()
      .ToTable("SectionType")
      .HasKey(st =&gt; st.EnumId);
  modelBuilder.Entity&lt;SectionType&gt;().Property(st =&gt; st.EnumId).IsRequired();
  </code></pre>
  
  <p>A couple of other points:</p>
  
  <ul>
  <li>I would prefer not to have a SectionType collection on the LocaleValueLookup object. LocaleValueLookup is a low-level class that a lot of other classes depend on, so to include a collection property on LocaleValueLookup for every other class that references it will make for an unwieldy class with a lot of collections on it that I don't need from a domain perspective.</li>
  <li>I would prefer to do the mapping setup in DbContext.OnModelCreating() rather than using attributes on my model objects</li>
  </ul>
  
  <p>Any help would be greatly appreciated!</p>