title: EntityFramework transaction rollback with multi table insert
body: <p><strong>Question: I need to get an identity back in a multi table insert, and I need to wrap transaction support around it in Entity Framework.</strong> </p>
  
  <p>I have two (psuedo generic) objects with corresponding tables, Book and Author:</p>
  
  <pre><code>create table Author
  (authorid int identity primary key,
  authorname varchar(max)
  )
  
  create table Book
  (bookid int identity primary key,
  bookname varchar(max),
  authorid int references Author(authorid)
  )
  </code></pre>
  
  <p>My problem is that when I need to insert a new book with a new author, I end up needing to do something like this, and if the Book insert throws an exception I have an Author with no Book which isn't good for my application.</p>
  
  <pre><code>context.Authors.Add(newauthor);
  context.SaveChanges();
  newbook.AuthorID = newauthor.ID //I can read this now because the SaveChanges() created the ID
  context.Books.Add(newbook);
  context.SaveChanges();
  </code></pre>
  
  <p>I skimmed over <a href="https://coderwall.com/p/jnniww" rel="nofollow noreferrer" title="this article">this article</a> which basically says to not use Transactions with EntityFramework and advises to call SaveChanges() once per operation and let EF handle transactions by itself. I'd love to, but I need to get the identity from the table back first, like indicated in my psuedo code and <a href="https://stackoverflow.com/questions/5212751/how-can-i-get-id-of-inserted-entity-in-entity-framework" title="this SO article">this SO question</a></p>