title: C# EF Code First 1:1 optional relationship foreign key property
body: <p>I am trying to create a relationship in EF where the foreign key is optional. For example like:
  <a href="https://stackoverflow.com/a/6023998/815553">https://stackoverflow.com/a/6023998/815553</a></p>
  
  <p>My question is, is there any way to do something like the above but where I can keep the ContactID property as part of the model?</p>
  
  <p>In my specific case I have a Person and a Voucher. The person table will have a VoucherId which is optional, as the voucher will only come in at a later stage to link up to the person.</p>
  
  <pre><code>public class Person
  {
      public int ID { get; set; }
      public string Name { get; set; }
      public string Surname { get; set; }
  
      public virtual Voucher Voucher { get; set; }
  }
  
  public class Voucher
  {
      public int ID { get; set; }
      public string VoucherCode { get; set; }
  }
  
  modelBuilder.Entity&lt;Person&gt;()
      .HasOptional(p =&gt; p.Voucher)
      .WithOptionalDependent().Map(a =&gt; a.MapKey("VoucherId"));
  </code></pre>
  
  <p>What I have here works, but what I want is yo have VoucherId in the Person class. As it stands in order to add a voucher to the person I have to give the entire Voucher object to the Voucher parameter.</p>
  
  <pre><code>using (DatabaseContext context = new DatabaseContext())
  {
      Voucher v = new Voucher()
      {
          VoucherCode = "23423"
      };
      context.Voucher.Add(v);
      context.SaveChanges();
      Person p = new Person()
      {
          Name = "Bob",
          Surname = "Smith",
          Voucher=v
      };
      context.Person.Add(p);
      context.SaveChanges();
  }
  </code></pre>
  
  <p>I want to be able to do:</p>
  
  <pre><code>Person p = new Person()
  {
      Name = "Bob",
      Surname = "Smith",
      VoucherId=v.ID // I wouldn't reference it like this, I would have the ID from a different source
  };
  </code></pre>