Which transaction is better with Dapper: BEGIN TRAN or TransactionScope?

白昼怎懂夜的黑 提交于 2019-12-09 22:33:07

问题


I've just started using Dapper and I was wondering which pattern for transactions would be better.

When I write SQL I prefer to use the transaction already in the script with:

BEGIN TRAN

-- insert, update etc.

COMMIT

because it's easier to test it but there is also the question transaction with dapper dot net where .net transactions are used so now I'm not sure which one I should actually use.

Does either method have any dis/advantages over the other?


回答1:


Actually, this has nothing to do with Dapper. Refer this answer.

TransactionScope or connection.BeginTransaction or "Transaction in stored procedure" decision is outside the scope of Dapper. Dapper simply exposes few extension methods on DBConnection object of ADO.NET those map the output of queries to object. Rest is up to you.

  1. TransactionScope is generally used for distributed transactions; transaction spanning different databases may be on different system. This needs some configurations on operating system and SQL Server without which this will not work. This is not recommended if all your queries are against single instance of database.
    As @ImrePühvel noted in comments: With single database this may be useful when you need to include the code in transaction that is not under your control. With single database, it does not need special configurations either.

  2. connection.BeginTransaction is ADO.NET syntax to implement transaction (in C#, VB.NET etc.) against single database. This does not work across multiple databases.

  3. "Transaction in stored procedure" is implemented against single database in Stored Procedure instead of doing this in application code.

Nested transactions or combination of above types is another topic for discussion; try searching net for this.

My personal opinion is to use UnitOfWork to handle transactions in better way. I have already mentioned the details in the link above. It uses connection.BeginTransaction internally.



来源:https://stackoverflow.com/questions/44118876/which-transaction-is-better-with-dapper-begin-tran-or-transactionscope

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