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
Userinto 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
Userrecords that get created? Or is there a better way?
You can use
System.Transactions.TransactionScopeto perform this all in an atomic transaction, but if you are using differentDataContextinstances, it will result in a distributed transaction, which is probably not what you really want.By the sounds of it, you’re not really implementing the repository pattern correctly. A repository should not create its own
DataContext(or connection object, or anything else) – these dependencies should be passed in via a constructor or public property. If you do this, you’ll have no problem sharing theDataContext:Use the same pattern for
ClubMemberRepository(or whatever you call it), and this becomes trivial:Of course, even this is a little bit iffy. If you have a foreign key in your database, then you shouldn’t even need two repositories, because Linq to SQL manages the relationship. The code to create should simply look like this:
Don’t fiddle with multiple repositories – let Linq to SQL handle the relationship for you, that’s what ORMs are for.