5

I am trying to execute sql inside a transaction using ServiceStack OrmLite. The code below works with Sqlite but not with SqlServer. With SqlServer I get the following error:

ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.

Is there something wrong with this code?

using (var trans = Db.BeginTransaction())
{
    try
    {
        foreach (myObject in myObjects)
            Db.Insert<MyObject>(myObject);
        trans.Commit();
    }
    catch (Exception ex)
    {
        trans.Rollback();
        throw ex;
    }
}
Brian Rice
  • 3,107
  • 1
  • 35
  • 53
  • Correct me if I'm wrong, but isn't it useless to call `Rolback()` in the catch block? I think as long as you don't commit it then the transaction won't go through. https://github.com/ServiceStack/ServiceStack.OrmLite/blob/6357d73e6615341e40f390c63364470be822a908/tests/ServiceStack.OrmLite.Tests/OrmLiteTransactionTests.cs#L44 – arjabbar Nov 16 '18 at 17:24
  • technically you probably don't have to in most cases, but seems like good form... and more about this here: https://stackoverflow.com/questions/7971903/do-i-need-to-call-rollback-if-i-never-commit – Brian Rice Nov 23 '18 at 19:00

1 Answers1

2

Someone else put this answer in a comment and then deleted it... so:

BeginTransaction needs to be OpenTransaction

Brian Rice
  • 3,107
  • 1
  • 35
  • 53
  • Because I couldn't find `OpenTransaction` in the current source code and didn't have the time to try the code. Which version are you using? – Panagiotis Kanavos May 29 '15 at 12:36
  • Right you need to use `db.OpenTransaction()`, examples on [OrmLite's Home Page](https://github.com/ServiceStack/ServiceStack.OrmLite#transaction-support). – mythz May 29 '15 at 13:55