Re: Getting Errors with Transaction
- From: "Jonathan Wood" <jwood@xxxxxxxxxxxxxxxx>
- Date: Thu, 14 Aug 2008 08:24:42 -0600
I see now the error is due to the fact that ExecScalar() returns null. I found several references that show that is the way to return the SCOPE_IDENTITY() of an inserted row. Guess I'll keep researching that one.
Jonathan
"Jonathan Wood" <jwood@xxxxxxxxxxxxxxxx> wrote in message news:%23mQWXid$IHA.1016@xxxxxxxxxxxxxxxxxxxxxxx
I wrote code to insert a record into a table. It worked fine. Then I added a transaction using code essentially like this:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DTSConnectionString"].ToString()))
{
conn.Open();
trans = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Contracts (Title, Description, StartDate, EndDate) VALUES (@Title, @Description, @StartDate, @EndDate)";
cmd.Parameters.Add(new SqlParameter("@Title", txtTitle.Text));
cmd.Parameters.Add(new SqlParameter("@Description", txtDescription.Text));
cmd.Parameters.Add(new SqlParameter("@StartDate", start));
cmd.Parameters.Add(new SqlParameter("@EndDate", end));
int contractId = (int)cmd.ExecuteScalar();
}
With this code, the call to ExecuteScaler() gives me the 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."
So, I tried adding the following line just before the call to ExecuteScaler():
cmd.Transaction = trans;
Now, the same call gives me the error "Object reference not set to an instance of an object."
I'm still a little new to this and just couldn't figure out exactly what I'm supposed to be doing here. I'd appreciate any help on this.
Thanks.
Jonathan
.
- Follow-Ups:
- Re: Getting Errors with Transaction
- From: Jim Rand
- Re: Getting Errors with Transaction
- References:
- Getting Errors with Transaction
- From: Jonathan Wood
- Getting Errors with Transaction
- Prev by Date: Re: ADO.NET Entities Failure (RTM)
- Next by Date: Re: Getting Errors with Transaction
- Previous by thread: Getting Errors with Transaction
- Next by thread: Re: Getting Errors with Transaction
- Index(es):
Relevant Pages
|