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.
I have two (psuedo generic) objects with corresponding tables, Book and Author:
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)
)
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.
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();
I skimmed over this article 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 this SO question