title: Entity framework, unit of work and the order of generated inserts statements
body: <p>I'm having a problem where I'm adding objects to the underlying persistence store (MS SQL Server 2012) using the repository and unit of work patterns. The problem is that once committed, the order of the insert statements generated comes in the wrong order and thus they fail due to foreign key constraints.</p>
  
  <p>Imagine that we want to create a customer, address, account and order with order lines in one go (a single commit):</p>
  
  <pre><code>using (var tx = new TransactionScope())
  {
      var address = new Address(...);
      _addressRepository.Add(address);
  
      var customer = new Customer(...);
      customer.AssignLegalAddress(address.Id);
      _customerRepository.Add(customer);
  
      var account = new Account(..., customer.Id);
      _accountRepository.Add(account);
  
      var order = new Order();
      order.AssignBuyerAccount(account.Id);
      order.AddOrderLine(...);
      order.AddOrderLine(...);
  
      _orderRepository.Add(order);
  
      _unitOfWork.Commit();
      tx.Complete();
  }
  </code></pre>
  
  <p>So in order for the Customer to be committed, the address should be committed first, and the customer before the account, and finally the account before the order. So the order in which I call Add on the different repositories.</p>
  
  <p>The repositories above uses Entity Framework 5.0 code first below, and each add operation comes down to adding the entity to the underlying DbContext. We could translate it to: <code>DbContext.Set&lt;TEntity&gt;().Add(entity)</code>.
  The call to Commit basically calls DbContext.SaveChanges().</p>
  
  <p>The problem is that EF does not seem to care in which order they were added.
  While monitoring the queries sent to the underlying store on Commit, I see that first the address is created, so far so good, but then the insert statement to create the account is executed. This fails because the customer haven't been created yet.</p>
  
  <p>Is there a way to make EF take the order in which they we're added into account while saving changes? Otherwise I would have to commit the changes manually, such as:</p>
  
  <pre><code>using (var tx = new TransactionScope())
  {
      var address = new Address(...);
      _addressRepository.Add(address);
  
      _unitOfWork.Commit();
  
      var customer = new Customer(...);
      customer.AssignLegalAddress(address.Id);
      _customerRepository.Add(customer);
  
      _unitOfWork.Commit();
  
      var account = new Account(..., customer.Id);
      _accountRepository.Add(account);
  
      _unitOfWork.Commit();
  
      var order = new Order();
      order.AssignBuyerAccount(account.Id);
      order.AddOrderLine(...);
      order.AddOrderLine(...);
  
      _orderRepository.Add(order);
  
      _unitOfWork.Commit();
      tx.Complete();
  }
  </code></pre>
  
  <p>But that hardly seems like a optimal solution. Any ideas?</p>