每5次迭代保存到数据库中,但如果迭代次数较少,会发生什么

  • 本文关键字:迭代 如果 保存 5次 数据库 c#
  • 更新时间 :
  • 英文 :


我从数据库中提取了100个项目,需要更新并保存回数据库。我想批量保存它们,所以基本上说每5秒保存一次。但如果我只有4张唱片呢?保存逻辑永远不会被命中。

.....
int i =0;
foreach (var item in records)
{
item.Property += 10;
if (i % 5 == 0 && i != 0) // if records contains 4 items this will never be saved
{
ctx.SaveChanges();
}
i++;
}

简单地尝试

int i = 0;
foreach (var item in records)
{
item.Property += 10;
if (i % 5 == 0 && i != 0) // if records contains 4 items this will never be saved
{
ctx.SaveChanges();
}
i++;
}
ctx.SaveChanges();

您需要在它之前添加一个条件,因为它也会在循环之后再次命中。

int i = 0;
foreach (var item in records)
{
item.Property += 10;
if (i % 5 == 0 && i != 0) // if records contains 4 items this will never be saved
{
ctx.SaveChanges();
}
i++;
}
if (records.Count() < 5) // if records contains less than 5 items -> save
{
ctx.SaveChanges();
}

试试这个:

int i = 0;
bool saved = true; 
foreach (var item in records)
{
item.Property += 10;
if (i % 5 == 0 && i != 0)
{
ctx.SaveChanges();
saved = true; 
}
else 
{
saved = false; 
}
i++;
}
if (!saved) // if there are any unsaved items then save it here
{
ctx.SaveChanges();
}

相关内容

最新更新