title: Entity Framework 4.1 Fluent mapping Foreign Key and the Foreign object with a string key
body: <p>I am moving from an EDMX mapping to the EF 4.1 DbContext and Fluent mapping and I am wanting to map both a string foreign key and the foreign object using the fluent API. I have an Employee with an Optional Office. I would like both the OfficeId and the Office Object in the Employee class (This is all read only, and I do not need to be able to save these objects). Objects with int keys work fine, but I have tried several with string keys and get the same result - the OfficeId field populates, but the Office object comes back as null. Chekcking in SQL profiler the data is being queried, but the office object is not being populated.</p>
  
  <pre><code>public partial class Employee
  {
      public int Id { get; set; }
      // snip irrelevant properties
      public Office Office { get; set; }  // this is (incorrectly) always null
      public string OfficeId { get; set; }
      public WorkGroup WorkGroup { get; set; } // this one with the int key is fine
      public int? WorkGroupId { get; set; }
      // snip more properties
  }
  
  public partial class Office
  {
      public string Id { get; set; }
      public string Description { get; set; }
  }
  
  public partial class WorkGroup
  {
      public int Id { get; set; }
      public string Code { get; set; }
  }
  </code></pre>
  
  <p>After feedback from Ladislav below, I map it like this in the OnModelCreating</p>
  
  <pre><code>modelBuilder.Entity&lt;Employee&gt;().HasKey(d =&gt; d.Id).ToTable("Employee", "ExpertQuery");
  modelBuilder.Entity&lt;Office&gt;().HasKey(d =&gt; d.Id).ToTable("Office", "ExpertQuery");
  modelBuilder.Entity&lt;WorkGroup&gt;().HasKey(d =&gt; d.Id).ToTable("WorkGroup", "ExpertQuery");
  
  modelBuilder.Entity&lt;Employee&gt;()
      .HasOptional(a =&gt; a.Office)
      .WithMany()
      .Map(x =&gt; x.MapKey("OfficeId")); // this one does not work
  modelBuilder.Entity&lt;Employee&gt;()
              .HasOptional(e =&gt; e.WorkGroup)
              .WithMany()
              .HasForeignKey(e =&gt; e.WorkGroupId); // this one works fine
  </code></pre>
  
  <p>I assume there is some subtlety with string keys that I am missing ? I am querying it as follows :</p>
  
  <pre><code>var employees = expertEntities.Employees.Include("Office").Include("WorkGroup").Take(10).ToList();
  </code></pre>
  
  <p>If I omit the OfficeId field from Employee, and set up the mapping like this :</p>
  
  <pre><code>modelBuilder.Entity&lt;Employee&gt;()
      .HasOptional(e =&gt; e.BusinessEntity)
      .WithMany()
      .Map(x =&gt; x.MapKey("OfficeId"));
  </code></pre>
  
  <p>Then the office object is populated, but I need the OfficeId field in the Employee object.</p>