none
MS CRM 2011 - Using xrmservicecontext updates all the fields for entity even if few fields are changed

    Question

  • Hi,

    I've a workflow created which get triggered on contact entity's FirstName, LastName field change and it creates a record of custom entity record. And there is a console application, which updates a custom field on contact entity. I am using early binding to update the contact record. But this is causing the workflow to run again  even though FirstName / LastName is changed and hence it's again creating a custom entity record (which i don't want).

    Does anyone have any idea to stop running the workflow again?

    Thanks,
    Abhi

    Wednesday, June 27, 2012 12:20 PM

Answers

  • Got the solution for this.

    The problem statement mentioned above is valid when we use following approach:

    Contact varEmployee = (from emp in xrm.ContactSet
                          where emp.Id.Equals(request.new_EmployeeId.Id)
                          select emp).FirstOrDefault();

    So, if we want to update any field on 'varEmployee' record, we usually write:

    varEmployee.Field1 = "Test";
    xrm.UpdateObject(varEmployee);
    xrm.SaveChanges();

    This actually causes every fields to be updated to crm DB and hence, all the underlying workflows on contact field change gets fired.

    So to avoid this, we can follow the steps as given below:

    Contact varEmployee = (from emp in xrm.ContactSet
                          where emp.Id.Equals(request.new_EmployeeId.Id)
                          select emp).FirstOrDefault();
                                    
    Contact newEmp = new Contact();
    newEmp.Id = varEmployee.Id;
    newEmp.ContactId = varEmployee.ContactId;
    
    // Update 'newEmp' object for any field change
    newEmp.Field1 = "Test";
    xrm.Update(newEmp);

    This way, xrm doesn't update the entire fields for the records. It just updates the updated field. So, all workflows won't get fired.

    Hope this would help!

    Thanks,
    Abhi




    • Marked as answer by Abhi D Wednesday, June 27, 2012 1:32 PM
    • Edited by Abhi D Wednesday, June 27, 2012 1:34 PM
    Wednesday, June 27, 2012 1:30 PM