Skip to main content
 首页 » 编程设计

c#之在 Entity Framework 6 的 foreach 循环中更新记录

2024年02月06日1752php

我在 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,这样它就不会在我的服务的下一次迭代中被选中。问题是我的方法不更新数据库,总是“捕获”我的所有记录。

请您参考如下方法:

正如评论中所讨论的,由于 Entity Framework 上下文(内部)使用了 Unit of Work模式,您只需要调用 SaveChanges() 一次,并且只需要在您完成修改所有项之后。

更多关于 MSDN