Entities may have been modified or deleted since entities were loaded. Error during transaction
<p>During the execution of the following piece of code, I get the message</p>

<blockquote>
  <p>Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.</p>
</blockquote>

<p>And there are loads of occurrences of that in here, but I didn't find a solution to my problem.</p>

<p>This only happens to me because I'm running <code>_db.SaveChanges()</code> two times inside one transaction (<code>_db</code> is my database context object), and I HAVE to do so because I need the generated ID that it gives me in order to proceed with the code.</p>

<p>If anyone can help me, I'd appreciate it. Also, if you know a way to proceed without the two <code>_db.SaveChanges()</code> or with a different way of approaching the transaction, I welcome you to show it. </p>

<pre><code>using (var trans = _db.Database.BeginTransaction())
{
    try
    {
        var f = cbxFornecedor.SelectedItem as Fornecedor;
        var c = new Compra
                {
                    CompraId = compra.CompraId,
                    DataCompra = dtpDataCompra.Value,
                    ListaProdutos = new List&lt;ListaProdutos&gt;(),
                    Fornecedor = f,
                    Referencia = tbxReferencia.Text,
                    Situacao = rbtEntregue.Checked
                };

        _db.Compras.Add(c);
        _db.SaveChanges();

        foreach (var cada in _itens)
            c.ListaProdutos.Add(new ListaProdutos
                    {
                        Compra = c,
                        CompraId = c.CompraId,
                        Produto = cada.ProdutoClasse,
                        ProdutoId = cada.ProdutoClasse.ProdutoId,
                        Valor = cada.ValorTotal,
                        Quantidade = cada.Quantidade,
                    });

        foreach (var cada in c.ListaProdutos)
            if (_db.ListaProdutos.Find(cada.CompraId, cada.ProdutoId) != null)
                _db.Entry(cada).State = EntityState.Modified;
            else
                _db.ListaProdutos.Add(cada);

        _db.Entry(c).State = EntityState.Modified;
        _db.SaveChanges();

        trans.Commit();
    }
    catch (Exception ex)
    {
        trans.Rollback();
        MessageBox.Show(this, ex.Message, @"Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
</code></pre>

<p>And, just to be clear, I know that my problem is with that fact that the transaction is there. I tried removing it and it worked. Also, if I take out the second <code>_db.SaveChanges()</code>, it works too.</p>

<p>The exception is only thrown in the second <code>_db.SaveChanges()</code>, and only if it is surrounded by the transaction block.</p>