我有一个需要写入sql数据库表的应用程序。需要对sql字符串的IN语句中使用的ID进行分块,因为IN中可能存在300k ID,这会使Web配置中的最大字符串长度溢出。当我尝试使用200 + k ID而不是50K ID左右的场景测试场景时,出现此错误:
与当前连接关联的事务已完成,但尚未处理。必须先处理事务,然后才能使用该连接执行SQL语句。
这是代码:
public int? MatchReconDetail(int ReconRuleNameID, List<int> participants, int? matchID, string userID, int FiscalPeriodID)
{
DataContext context = new DataContext();
context.CommandTimeout = 600;
using (TransactionScope transaction = new TransactionScope())
{
Match dbMatch = new Match() { AppUserIDMatchedBy = userID, FiscalPeriodID = FiscalPeriodID, DateCreated = DateTime.Now };
context.Matches.InsertOnSubmit(dbMatch);
context.SubmitChanges();
//string ids = string.Concat(participants.Select(rid => string.Format("{0}, ", rid))).TrimEnd(new char[] { ' ', ',' });
int listCount = participants.Count;
int listChunk = listCount / 1000;
int count = 0;
int countLimit = 1000;
for (int x = 0; x <= listChunk; x++)
{
count = 1000 * x;
countLimit = 1000 * (x + 1);
List<string> chunkList = new List<string>();
for (int i = count; i < countLimit; i++)
{
if (listCount - count < 1000 && listCount - count != 0)
{
int remainder = listCount - count;
for (int r = 0; r < remainder; r++)
{
chunkList.Add(participants[count].ToString());
count++;
}
}
else if (listCount - count >= 1000)
{
chunkList.Add(participants[i].ToString());
}
}
string ids = string.Concat(chunkList.Select(rid => string.Format("{0}, ", rid))).TrimEnd(new char[] { ' ', ',' });
string sqlMatch = string.Format("UPDATE [Cars3]..[ReconDetail] SET [MatchID] = {0} WHERE [ID] IN ({1})", dbMatch.ID, ids);
context.ExecuteCommand(sqlMatch);
}
matchID = dbMatch.ID;
context.udpUpdateSummaryCache(FiscalPeriodID, ReconRuleNameID, false);
transaction.Complete();
}
return matchID;
}
}
我已经阅读了一些有关超时问题的文章,因此在此函数的顶部添加了context.CommandTimeout。事件触发大约一分钟后,似乎发生了错误。
任何想法将不胜感激。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句