title: Entity Framework, code first using fluent API, avoid inserting in referenced table
body: <p>I have a table named <strong>ServiceProviders</strong> with static data. The POCO class is follows</p>
  
  <pre><code>public class ServiceProvider
      {
           public virtual int Id
          {
              get;
              set;
          }
  
          public virtual string Name
          {
              get;
              set;
          }
   }
  </code></pre>
  
  <p>I have a <strong>Client</strong> table. Each client needs to have a reference to one of the "existing" service providers.</p>
  
  <pre><code>    public class Client
          {
           public virtual int Id
          {
              get;
              set;
          }    
  
          public virtual string FirstName
          {
              get;
              set;
          }
  
          public virtual string LastName
          {
              get;
              set;
          }
  
          public virtual ServiceProvider ServiceProvider
          {
              get;
              set;
          }
  }
  </code></pre>
  
  <p>I am configuring the client using EF code first fluent API as follows </p>
  
  <pre><code>public ClientConfiguration(): base()
          {
              HasKey(e =&gt; e.Id);
              Property(e =&gt; e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
              ToTable("dbo.Clients");
              Property(e =&gt; e.FirstName).IsRequired().HasMaxLength(256).IsVariableLength().HasColumnType("nvarchar");
              Property(e =&gt; e.LastName).IsRequired().HasMaxLength(256).IsVariableLength().HasColumnType("nvarchar");
              HasRequired(e =&gt; e.ServiceProvider).WithMany().Map(m =&gt; m.MapKey("ServiceProviderId")).WillCascadeOnDelete(false);
  }
  </code></pre>
  
  <p>When I want to insert a new client's record, I get a reference of an existing <strong>ServiceProvider</strong> instance and attach it to the Client's <strong>ServiceProvider</strong> property</p>
  
  <pre><code>Client client = new Client() { FirstName = "John", LastName = "Doe" };
  client.ServiceProvider = serviceproviders[0]; //An existing ServiceProvider instance fetched from DB earlier
  </code></pre>
  
  <p>When I call SaveChanges, EF inserts a new (duplicate) record in my <strong>ServiceProviders</strong> table. All I want it to do is to insert a new record only in the <strong>Client</strong> Table and set the value of <strong>ServiceProviderId</strong> column to the existing ServiceProvider instance's <strong>Id</strong>.</p>
  
  <p>What am I doing wrong?</p>