2014-10-11 146 views
0

試圖更新事件記錄列表。在foreach中的第一個更新中,下一個拋出一個異常,指出「上下文當前沒有跟蹤事件實體」。這是對此進行編碼的正確方法嗎?Dynamics CRM Linq更新多條記錄

var openCases = (from o in xrmContext.IncidentSet 
        where o.StateCode == 0 
        select o).Take(5).ToList(); 

       foreach (var c in openCases) 
       { 
        var numDays = ((TimeSpan) (DateTime.Now - c.CreatedOn)).Days; 
        Console.WriteLine("case age: {0}, case number:{1}", numDays, c.TicketNumber); 
        c.new_caseage = numDays; 
        xrmContext.UpdateObject(c); 
        xrmContext.SaveChanges(); 
       } 

回答

1

當你調用SaveChanges()它,除了保存任何修改的實體記錄,在分離的背景下正在跟蹤的所有實體記錄。因此,第二次您撥打SaveChanges()實體記錄不被跟蹤,並且您收到錯誤。

您應該將xrmContext.SaveChanges();行移動到foreach循環之後。

  var openCases = (from o in xrmContext.IncidentSet 
      where o.StateCode == 0 
      select o).Take(5).ToList(); 

      foreach (var c in openCases) 
      { 
       var numDays = ((TimeSpan) (DateTime.Now - c.CreatedOn)).Days; 
       Console.WriteLine("case age: {0}, case number:{1}", numDays, c.TicketNumber); 
       c.new_caseage = numDays; 
       xrmContext.UpdateObject(c); 
      } 
      xrmContext.SaveChanges(); 
0

一種更好的方式做你嘗試做的是使用消息ExecuteMultipleRequest,它可以配置多少紀錄爲每一個迭代過程(內部迭代)

var openCases = (from o in xrmContext.IncidentSet 
        where o.StateCode == 0 
        select o).Take(5).ToList(); 

var requestWithResults = new ExecuteMultipleRequest() 
    { 
     // Assign settings that define execution behavior: continue on error, return responses. 
     Settings = new ExecuteMultipleSettings() 
     { 
      ContinueOnError = false, 
      ReturnResponses = true 
     }, 
     // Create an empty organization request collection. 
     Requests = new OrganizationRequestCollection() 
    }; 

    foreach (var c in openCases) 
    { 
     var numDays = ((TimeSpan) (DateTime.Now - c.CreatedOn)).Days; 
     c.new_caseage = numDays; 

     CreateRequest createRequest = new CreateRequest { Target = c }; 
     requestWithResults.Requests.Add(createRequest); 
    } 

    ExecuteMultipleResponse responseWithResults = 
    (ExecuteMultipleResponse)_serviceProxy.Execute(requestWithResults); 

希望它有幫助