我有一个服务,它使用3个方法(每个方法调用另一个方法)将数据插入到sql azure中的3个表中。前两个方法正确插入数据,但接收前两个表的索引的第三个方法(其他两个的关系)不正确。这些方法类似于:
public int InsertTableOne([FromBody]Object obj)
{
int IdTableOne = 0;
tring connectionString = WebConfigurationManager.AppSettings["MyString"];
string queryString = "INSERT INTO TableOne (Name,Phone OUTPUT INSERTED.IdTableOne VALUES (@Name,@Phone) ";
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlTransaction tran = connection.BeginTransaction())
{
using (SqlCommand comm = new SqlCommand(queryString, con, tran))
{
try
{
command.Parameters.AddWithValue("@Name", obj.Name);
command.Parameters.AddWithValue("@Phone",obj.Phone);
IdTableOne = Convert.ToInt32(command.ExecuteScalar());
InsertTableTwo(obj,IdTableOne)
tran.Commit();
}
catch()...
finally
{
con.Close();
}
}
}
}
}
public int InsertTableTwo([FromBody] ob obj,List<listOfElements> listofThings,int IdTableOne)
{
int IdTableTwo = 0;
string queryString = "INSERT INTO TableTwo (Car,Color) OUTPUT INSERTED.IdTableTwo VALUES(@Car,@Color)";
string connectionString = WebConfigurationManager.AppSettings["MyString"];
using (SqlConnection con = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand comm = new SqlCommand(queryString, con))
{
try
{
command.Parameters.AddWithValue("@Car","" );
command.Parameters.AddWithValue("@Color", "");
foreach (listOfElements thing in (listofThings))
{
command.Parameters["@Car"].Value = GetCar(thing.Car);//Methodo to get the car, works fine
command.Parameters["@Color"].Value = thing.Color;
IdTableTwo = Convert.ToInt32(command.ExecuteScalar());
InsertTableThree(IdTableOne, IdTableTwo);
}
}
catch()...
}
}
return IdTableTwo;
}
public int InsertTableThree(int IdTableOne,int IdTableTwo)
{
string connectionString = WebConfigurationManager.AppSettings["MyString"];
string queryString = "INSERT INTO TableThree (IdTableOne,IdTableTwo) VALUES(@IdTableOne,@IdTableTwo)";
using (SqlConnection con = new SqlConnection(connectionString))
{
//connection.Open();
using (SqlCommand comm = new SqlCommand(queryString, con))
{
try
{
command.Parameters.AddWithValue("@IdTableOne", IdTableOne);
command.Parameters.AddWithValue("@IdTableTwo", IdTableTwo);
command.Parameters.Clear();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
return IdTableOne;
}
最后,前两个表接收数据,但最后一个表仍然为空,没有索引。数据库、事务或代码没有崩溃。唯一的问题是最后一个表数据。此外,当我调试它时,索引的值在应该插入时是正确的。