title: Entity Framework: insert an object with a foreign key which is already known, but doesn't exist in DB yet
body: <p>I'm using Entity Framework and would like to insert an object into the database that references another object that doesn't exist in the DB yet (but the foreign key is known already).</p>
  
  <p>Simple example: assume I have two tables, <code>Books</code> (identified by their ISBN) and <code>Purchases</code>. I'd like to be able to insert purchases, even if the book hasn't been set up in the DB yet:</p>
  
  <pre><code>public class Book
  {
      [Key]
      public virtual string ISBN { get; set; }
  
      protected virtual IEnumerable&lt;Purchase&gt; purchases { get; set; }
  
      public virtual string author { get; set; }
      public virtual string title { get; set; }
  // .....
  }
  
  public class Purchase
  {
      [Key]
      protected virtual int id { get; set; }
  
      public virtual Book book { get; set; }
  
      public virtual double price;
  }
  </code></pre>
  
  <p>Conceptually, this would be easy: the <code>Purchase</code> table will have a foreign key that is the book's ISBN. So in regular SQL, I could just insert the ISBN into this field, and add the book to the books table sometime later.</p>
  
  <p>In EF/C# though, I can't think of an easy way to do this. The <code>Purchase</code> class references the <code>Book</code> class, so I can't just use the ID (ISBN) directly here.</p>
  
  <p>What I could do is create a dummy book object and use this to insert the purchase. Problem is that Entity Framework automatically inserts the dummy book object into the table too, which I want to avoid:</p>
  
  <pre><code>var dummyBook = new Book();
  dummyBook.isbn = "978-0141354217";
  
  var purchase = new Purchase();
  purchase.price = 99.95;
  purchase.book = dummyBook;
  
  dbContext.Purchases.Add(purchase);
  
  // Should add the purchase to the DB, but NOT the book!
  // Unfortunately, EF adds both automatically...
  dbContext.SaveChanges();
  </code></pre>
  
  <p>Is there any way to do this?</p>
  
  <p>Thanks!</p>