Dynamics CRM Linq更新多个记录

时间:2014-10-11 21:45:54

标签: linq dynamics-crm

尝试更新事件记录列表。 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();
                }

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

调用SaveChanges方法后,OrganizationServiceContext将分离所有实体。要继续对先前检索的实体使用数据上下文,需要重新附加实体。

但是,首选是在一次调用SaveChanges时应用所有修改,然后处理上下文,以避免重新附加。

http://msdn.microsoft.com/en-us/library/gg695783.aspx

http://msdn.microsoft.com/en-us/library/gg334504.aspx#track_related

答案 2 :(得分: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);

希望有所帮助