I have a User
table and a ClubMember
table in my database. There is a one-to-one mapping between users and club members, so every time I insert a ClubMember
, I need to insert a User
first. This is implemented with a foreign key on ClubMember
(UserId REFERENCES User (Id)
).
Over in my ASP.NET MVC app, I'm using LinqToSql and the Repository Pattern to handle my persistence logic. The way I currently have this implemented, my User
and ClubMember
transactions are handled by separate repository classes, each of which uses its own DataContext
instance.
This works fine if there are no database errors, but I'm concerned that I'll be left with orphaned User
records if any ClubMember
insertions fail.
To solve this, I'm considering switching to a single DataContext
, which I could load up with both inserts then call DataContext.SubmitChanges()
only once. The problem with this, however, is that the Id
for User
is not assigned until the User
is inserted into the database, and I can't insert a ClubMember
until I know the UserId
.
Questions:
Is it possible to insert the
User
into the database, obtain theId
, then insert theClubMember
, all as a single transaction (which can be rolled back if anything goes wrong with any part of the transaction)? If yes, how?If not, is my only recourse to manually delete any orphaned
User
records that get created? Or is there a better way?