0

I was reading up on this and it seemed like I shouldn't have to call scope.Complete for the following code to work.

When I try running this without using scope.Complete() the records are saved to the database. If scope.Complete() is there the records save and everything works.

public static void SaveProducts(IList<Product> products)
{
    using (TransactionScope scope = new TransactionScope())
    {
        using (var connection = GetOpenConnection())
        {
            StringBuilder sqlDelete = new StringBuilder();
            sqlDelete.AppendLine("MY SQL STATEMENT HERE ");

            StringBuilder sqlInsert = new StringBuilder();
            sqlInsert.AppendLine("MY SQL STATEMENT HERE ");


            connection.Execute(sqlDelete.ToString(), new { CategoryId = categoryId });
            connection.Execute(sqlInsert.ToString(), products);

        }

        scope.Complete();
    }
}
Matthew Peterson
  • 325
  • 1
  • 4
  • 18
  • I think I misread your original statement and went with context...are you saying that the records **are** saved if you **don't** call scope.Complete()? Actually, I didn't misread it...it seems to be contradictory: "When I try running this without using scope.Complete() the records are saved to the database, when it isn't there nothing happens." Both are saying when scope.Complete isn't there! –  Aug 11 '15 at 20:27
  • Sorry, I meant to say that when I do not call scope.Complete(), nothing happens. I updated my post, sorry it has been a long day. – Matthew Peterson Aug 11 '15 at 20:56
  • I got confused for a sec! I would also point out that you should be careful with adding the strings like this and be sure that you use parameterized queries. Otherwise, you'll be susceptible to sql injection. –  Aug 11 '15 at 20:58
  • I might be misunderstanding what you are saying, but I am using Dapper so shouldn't that handle sql injection? My queries all use parameters as you can see in my example I am sending in categoryId which replaces @CategoryId in the query. Does this make sense? – Matthew Peterson Aug 11 '15 at 21:38
  • I think I was just focusing in on the StringBuilder class + SQL which to me equals danger! I've never used Dapper before, but if that is how they do parameterized queries, then you should be good-to-go. (Dapper should be fine for combating SQL injection: http://stackoverflow.com/questions/13653461/dapper-and-sql-injections) –  Aug 11 '15 at 21:45

1 Answers1

1

Per the doc:

Failing to call this method aborts the transaction, because the transaction manager interprets this as a system failure, or exceptions thrown within the scope of transaction.

I think it's saying that if there is something that goes wrong, it will be disposed before the complete is signaled.