我从数据库中提取了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();
}