我在foreach循环中更新记录时遇到问题。我有一个从SQL表导出文件并将它们保存在网络共享上的方法:
public static void SyncOpportunity()
{
using (var ctx = new BPMOnline74Entities())
{
logger.Debug("Importing files from Opportunities.");
var oppFiles = from o in ctx.OpportunityFile
where SqlFunctions.DataLength(o.Data) > 0 && o.ServiceProcessed == false
select o;
foreach (OpportunityFile opp in oppFiles)
{
logger.Debug(string.Format("{0} is being imported.", opp.Name));
string fileName="";
if (opp.OpportunityId == null)
{
fileName = "E:\\BPM\\Opportunity\\";
logger.Error("File not bound to any DB object. Saved in E:\\BPM\\Opportunity.");
}
else
{
try
{
fileName = PathInfo.GetPath("Opportunity", (Guid)opp.OpportunityId);
}
catch (Exception ex)
{
logger.Error(ex.Message.ToString());
}
}
try
{
File.WriteAllBytes(fileName + opp.Name, opp.Data);
logger.Debug(string.Format("{0} was exported from SQL.", opp.Name));
opp.ServiceProcessed = true;
ctx.Entry(opp).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
}
catch(Exception ex)
{
logger.Error(ex.Message.ToString());
}
}
logger.Debug(string.Format("Imported {0} files.", oppFiles.Count().ToString()));
}
logger.Debug("Disposing SyncOpportunity.");
}
从SQL成功导出文件后,我想更新记录" ServiceProcessed"字段为true,因此在我的服务的下一次迭代中不会被选中。问题是我的方法不会更新数据库,而且总是会捕获"我的所有记录。
答案 0 :(得分:4)
正如评论中所讨论的,由于实体框架上下文是(内部)使用Here is an example of how you can do this模式,因此您只需要调用{{1}}一次,而之后只需#39 ;已完成修改所有项目。
更多关于Unit of Work