You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC 5 ActionResult中C#循环报错,求技术专家解答

ASP.NET MVC 5批量插入SQL报错排查与解决

我在ASP.NET MVC 5的ActionResult中编写了一段C#循环代码,用于执行SQL批量插入操作,但运行时抛出错误。

原始代码

int total = Convert.ToInt32(form["REC-tr-total"]); 
int value = 0;
string insValOutput = ""; 

if (total > 0)
{
  for (int i = 1; i <= total; i++) 
  {
    value = Convert.ToInt32(form["inventoryID[" + i + "]"]); 
    insValOutput = $"(" + vCAS_capture_payments.Id + ", value{i + 1}),"; 
  }

db.Database.ExecuteSqlCommand(String.Format(@"INSERT INTO dbo.VCAS_capture_payments__REF_items (FK_capture_paymentsId, FK_inventoryId)                 VALUES {0};", insValOutput));             
}

错误信息

错误信息截图

这看起来是个简单的循环,但错误持续出现,恳请专家指导。

更新1

按照建议修改了如下代码行,但仍出现相同错误:

insValOutput = String.Format(@"({0},{1}),", vCAS_capture_payments.Id, value);  // (1, value1),(2, value2) ...

更新2

感谢各位建议,我知道当前代码并非最优,但我一直在现有代码库中尝试通过LinQ和Entity Framework实现批量插入。

根据提供的解决方案修改代码后,现在可以正常运行。问题出在SQL语句和字符串拼接上。

修改后的正确代码

int total = Convert.ToInt32(form["REC-tr-total"]); // -- Total Receipt item rows
int value = 0;
string insValOutput = ""; // -- Insert VALUES variable

if (total > 0)
{
    for (int i = 1; i <= total; i++)
    {
        value = Convert.ToInt32(form["inventoryID["+i+"]"]); // -- Fetch the inventory ID for index i   
        insValOutput += String.Format(@"({0},{1}),", vCAS_capture_payments.Id, value);  // (1, value1),(2, value2) ...
    }

    db.Database.ExecuteSqlCommand(String.Format(@"
                    INSERT INTO dbo.VCAS_capture_payments__REF_items (FK_capture_paymentsId, FK_inventoryId)
                    VALUES {0};", insValOutput.TrimEnd(',', ' ')));
}

内容的提问来源于stack exchange,提问作者Austin Lazarus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:38:17