简体   繁体   中英

Transaction becomes null after SqlCommand.ExecuteScalar is run

I have a table in SQL Server defined as follows

create table Customer (ID varchar(10), Name varchar(200))

Insert into Customer 
values ('00001', 'Cust1'), ('ID00002', 'Cust2')

When I query customer name using ID (with wrong datatype, it is varchar , but its value is passed as int ), the command returns correct name, but its transaction becomes null, and on trying to commit, I get an error

InvalidOperationException
This SqlTransaction has completed; it is no longer usable.

My code:

using (var conn = new SqlConnection(connString))
{
    conn.Open();

    using (var trans = conn.BeginTransaction())
    {
        using (var cmd = new SqlCommand("SELECT Name FROM Customer WHERE ID = 1")) // After this command is executed, its transaction becomes null.
        //using (var cmd = new SqlCommand("SELECT Name FROM Customer  WHERE ID = '000001'")) // This runs fine.
        {
            cmd.Connection = conn;
            cmd.Transaction = trans;
            var res = cmd.ExecuteScalar();
        }

        trans.Commit(); 
    }
}

Is there anything I can do to check such scenario, and fail it when the command executes, instead of getting exception at later stage?

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

You Try This Code

  using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SchoolPlusDBContext"].ConnectionString))
        {
            conn.Open();

            using (var trans = conn.BeginTransaction())
            {
                using (var cmd = new SqlCommand("SELECT Name FROM Customer where  ISNUMERIC(id)=1 and Id=1")) // After this command is executed, its transaction becomes null.
                //using (var cmd = new SqlCommand("SELECT Name FROM Customer  WHERE ID = '000001'")) // This runs fine.
                {
                    cmd.Connection = conn;
                    cmd.Transaction = trans;
                    var res = cmd.ExecuteScalar();
                }

                trans.Commit();
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM