插入数据库仅在我第一次启动 ASP.NET 应用程序时执行?

Insert in Database is executed only the first time I start the ASP.NET application?

我的问题是,在我的 ASP.NET 应用程序中,仅在应用程序启动时第一次执行使用表单中的数据插入数据库。在那之后,插入也没有完成。

我尝试调试应用程序,在调试模式下每次都会插入数据。我还使用了 SQL Server profiler,除了我第一次在数据库中提交表单外,没有在数据库中插入任何内容。但是当我 运行 在调试模式下时,插入没有任何问题。

这是控制器的方法:

[HttpPost]
public ActionResult Form(Product p)
{
    IO.Insert(p);
    return RedirectToAction("Index");
} 

这是执行插入的方法:

public static void Insert(Product pr)
{
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["Database"]))
    {
        connection.Open();

        string s = "INSERT INTO Product (Id, Name, Price, Description, Category, Image) VALUES (@GUID, @Name, @Price, @Description, @Category, @Image)";

        using (SqlCommand cmd = new SqlCommand(s, connection))
        {
            cmd.Parameters.Add("@GUID", SqlDbType.UniqueIdentifier).Value = new Guid();
            cmd.Parameters.Add("@Name", SqlDbType.NChar).Value = pr.Name;
            cmd.Parameters.Add("@Price", SqlDbType.Int).Value = pr.Price;
            cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value = pr.Description;
            cmd.Parameters.Add("@Category", SqlDbType.NVarChar).Value = pr.Description;
            cmd.Parameters.Add("@Image", SqlDbType.VarBinary).Value = IO.ImageInsert(pr.Picture);

            cmd.BeginExecuteNonQuery();
        }
    }
}

此外,除了主线程,我没有使用任何其他线程。

您在 using 块中有命令,cmd.BeginExecuteNonQuery(); 启动异步执行 Transact-SQL 语句或此 SqlCommand 描述的存储过程。您不是在等待它完成,也不是通过轮询来确定命令是否已完成,使用 BeginExecuteNonQuery 方法返回的 IAsyncResultIsCompleted 属性 或使用 AsyncWaitHandle 属性 返回的 IAsyncResult.

您可以如下更改代码以等待命令执行。

IAsyncResult result = cmd.BeginExecuteNonQuery();

while (!result.IsCompleted)
{
   // Wait till the command executes
   Console.WriteLine("Waiting for query execution");
}
Console.WriteLine("Command complete. Affected {0} rows.", cmd.EndExecuteNonQuery(result));

根据微软

The BeginExecuteNonQuery method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the EndExecuteNonQuery method to finish the operation. The BeginExecuteNonQuery method returns immediately, but until the code executes the corresponding EndExecuteNonQuery method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same SqlCommand object. Calling the EndExecuteNonQuery before the command's execution is completed causes the SqlCommand object to block until the execution is finished.

您可以使用 ExecuteNonQuery 而不是 BeginExecuteNonQuery,因为您正在关闭连接并且查询仍然 运行。

cmd.ExecuteNonQuery() 用于单个插入或者您可以使用线程池

ThreadPool.QueueUserWorkItem(delegate {
using (SqlConnection sqlConnection = new SqlConnection("blahblah;Asynchronous Processing=true;") {
    using (SqlCommand command = new SqlCommand("someProcedureName", sqlConnection)) {
        sqlConnection.Open();

        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.AddWithValue("@param1", param1);

        command.ExecuteNonQuery();
    }
}});