4
votes

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;
    }
}
1
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. github.com/ServiceStack/ServiceStack.OrmLite/blob/… - arjabbar
technically you probably don't have to in most cases, but seems like good form... and more about this here: stackoverflow.com/questions/7971903/… - Brian Rice

1 Answers

2
votes

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

BeginTransaction needs to be OpenTransaction