ExecuteNonQuery导致数据库

时间:2018-04-20 17:52:48

标签: c# sql

我有一个使用sql查询字符串更新记录的函数,由ExecuteNonQuery执行。问题是,当此函数必须更新记录列表时,它会复制列表中最后一条记录的每个插入。

基于这个问题Code repeating itself causing duplicate records in database,我认为它与多线程和创建事务有关,但我不完全确定,因为我不熟悉创建锁,等

调用方法的地方:

foreach (var detail in report.Details)
        {
            detail.ShiftReportId = report.ShiftReportId;
            UpdateShiftReportDetail(detail);
        }

方法:

private void UpdateShiftReportDetail(ShiftReportDetail detail)
    {
        StringBuilder queryString = new StringBuilder();
        queryString.Append("Update ShiftReportDetails ")
            .Append("Set ShiftReportId = @ShiftReportId, LineNumber = @LineNumber, Produced = @Produced, Scrap = @Scrap, DownTime = @Downtime, Gauge = @Gauge, PerHour = @PerHour, Cast = @Cast, Target = @Target, Variance = @Variance, Notes = @Notes, PrimaryItem = @PrimaryItem, SecondaryItem = @SecondaryItem, Details = @Details, LineID = @LineId")
            .Append(" Where ShiftReportID = @ShiftReportId");

        // Create a connection.
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            SqlCommand command = new SqlCommand(queryString.ToString(), connection);
            command.Parameters.AddWithValue("@ShiftReportId", detail.ShiftReportId);
            command.Parameters.AddWithValue("@LineNumber", detail.LineNumber);
            command.Parameters.AddWithValue("@Produced", detail.Produced);
            command.Parameters.AddWithValue("@Scrap", detail.Scrap ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@Downtime", detail.DownTime ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@Gauge", detail.Gauge ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@PerHour", detail.PerHour ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@Cast", detail.Cast ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@Target", detail.Target ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@Variance", detail.Variance ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@Notes", detail.Notes ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@PrimaryItem", detail.PrimaryItem ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@SecondaryItem", detail.SecondaryItem ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@Details", detail.Details ?? (object)DBNull.Value);
            command.Parameters.AddWithValue("@LineId", detail.LineId);

            connection.Open();

            // Execute the command.
            command.ExecuteNonQuery();
        }
    }

0 个答案:

没有答案