Is it good practice to always use a TransactionScope in a DAL base class?

匆匆过客 提交于 2019-12-24 01:06:12

问题


I have a DAL base class which centralises all the database calling code in my app. I want to ensure that all insert/update/delete actions are wrapped in a transaction, irrespective of whether it was written into the SP or not. Would it be good practice to wrap my 'ExecuteNonQuery' DAL method in a TransactionScope or would I be adding a lot of overhead for db calls that don't require it.

I'm happy with using a TransactionScope furthur up the in the UI when required to wrap multiple service calls, it's really just enforcing it at the SP level i'm not sure about.

Im using .net 3.5 and mostly SQLServer 2008, some clients still use 2005 - hoping to move these over soon.

Thanks


回答1:


Tsansactions (and in particular heavy-weights like TransactionScope, even with the LTM) mainly kick in when applying multiple operations, which may span more than one db call.

Adding transactions can be important, but it changes the nature of the query; you could introduce deadlocks being the most obvious, but you could also change an intended side-effect of a method that is faulting. It could also fix an otherwise unintended side-effect. It changes the locking profile, and it has different system requirements (DTC enabled being the most obvious).

So don't idly add them.

Equally, a lot of read-only view screens don't need any special locking; heck, most list/search/etc wouldn't change in any important way if you saw an in-progress transaction with phantom/dirty/non-repeatable/etc data.

Personally, back when I was using SP-based code, I didn't tend to put the transaction management in the SP - it is often both easier and more appropriate to move that up to a higher level with more sophisticated fault management - i.e. pretty much anything except TSQL, which isn't intended to be good at procedural plumbing code like that. It is good at set-based DML, obviously.




回答2:


All single statement DML operations are transactions. Using TransactionScope in my opinion makes sense if you want to execute more than one statement in operation, like updating master record and then related child records. I would leave this decision to the user of your code rather than enforce using it implicitly. If you have stored procedure again, it is not necessarily the intention of the procedure creator to have all operations in one transaction. Wrapping everything in one transaction may actually lead to log file size explosion and concurrency problems.

Regards

Piotr



来源:https://stackoverflow.com/questions/6151986/is-it-good-practice-to-always-use-a-transactionscope-in-a-dal-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!