How can I wrap a transaction around Membership.CreateUser?
-
03-07-2019 - |
Question
I'm using the asp.net SqlMembershipProvider and LinqToSql in a hobby/learning application. I have some user properties that I'm keeping in LinqtoSql, so my flow is: Membership.CreateUser -> MyClass.AddUserDetails. I'd like to wrap the whole thing in a transaction, so if the myclass bit fails I can roll back the membership bit. Any suggestions on how to do so?
Solution
The providers don't explicitly support transactions, I asked for this feature some time ago:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=102268
I think if you use the TransactionScope class it should work, though you will have the overhead of an MSDTC-coordinated transaction.
OTHER TIPS
My real life experience (happened more than once):
- Junior programmer writes a site.
- During code review, I catch the missing transaction between user creation and profile creation (typically with a custom SqlProvider)
- We wrap everything in a DTC transaction.
- Nothing works on junior programmer's computer.
- Fix DTC on junior programmer's computer.
- Deploy to shared hosting environment.
- Nothing works in hosting environment.
- Argue for 4 hours with hosting company trying to fix their DTC.
- Remove transaction because site has to go online.
- Pray.
I don't really like membership anymore...
You can set the Transaction property of the DataContext to make it participate in a transaction you already have.