父表始终插入重复行

时间:2019-01-20 05:17:20

标签: c# sql sql-server asp.net-mvc

我在事务块中有以下代码。下订单时,我的基表(TBL_T_Orders)总是插入2个相同的行(重复的行具有不同的OrderId)。详细信息表TBL_T_OrderItems已正确插入项目。

我的代码

public CartTotal InsertNewOrder(CartTotal cartTotal)
{
            try
            {
                con.Open();

                transaction = con.BeginTransaction();

                string orderQuery = @"INSERT INTO [dbo].[TBL_T_Orders] ([OrderCode],[OrderReceivedDate]) 
                                      OUTPUT INSERTED.OrderId
                                      VALUES (@OrderCode, @OrderReceivedDate)";
                cmd = db.GetSqlStringCommand(orderQuery);
                cmd.Transaction = transaction;

                db.AddInParameter(cmd, "OrderCode", DbType.Int32, cartTotal.OrderCode);
                db.AddInParameter(cmd, "OrderReceivedDate", DbType.DateTime,DateTime.Now);

                db.ExecuteNonQuery(cmd, transaction);

                int OrderId = (int)cmd.ExecuteScalar();

                foreach (var item in cartTotal.items)
                {
                    string orderItemsQuery = @"INSERT INTO [dbo].[TBL_T_OrderItems] ([OrderId], [ItemId]
                                               VALUES (@OrderId, @ItemId)";

                    cmd = db.GetSqlStringCommand(orderItemsQuery);
                    cmd.Transaction = transaction;

                    db.AddInParameter(cmd, "OrderId", DbType.Int32, OrderId);//temp
                    db.AddInParameter(cmd, "ItemId", DbType.String, item.ItemId);

                    db.ExecuteNonQuery(cmd, transaction);
                }

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex;
            }
            finally
            {
                con.Close();
            }

            return cartTotal;
}

1 个答案:

答案 0 :(得分:1)

由于两次执行查询,因此您得到重复的条目。第一次使用db.ExecuteNonQuery,然后第二次使用cmd.ExecuteScalar();

删除第一行db.ExecuteNonQuery。然后它将完美运行。