D365: ExecuteMultiple error EntityState must be set to null, Created (for Create message) or Changed (for Update message)

While working on bulk update recently, we got an error saying “EntityState must be set to null, Created (for Create message) or Changed (for Update message)” in the ExecuteMultipleResponse object.

We were trying to update one attribute of a set of records and below is the piece code we were using to do bulk update:

  using (var ctx = new CrmServiceContext(service))
                var lines = (from s in ctx.dxc_revenueschedulelineSet
                             where s.StateCode == dxc_revenueschedulelineState.Active
                             && s.dxc_ClientId.Id == serviceEntryDetail.dxc_ClientID.Id
                             select s).ToList();

                if (lines == null || lines.Count <= 0) return;

                var multipleRequest = new ExecuteMultipleRequest()
                    Settings = new ExecuteMultipleSettings()
                        ContinueOnError = true,
                        ReturnResponses = true
                    Requests = new OrganizationRequestCollection()

                foreach (var line in lines)
                    UpdateRequest updateRequest = new UpdateRequest { Target = line };
                    line.dxc_EndDate = serviceEntryDetail.dxc_DepartureDate;

                ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

Using Update message inside foreach loop to update each record instead of using ExecuteMultiple worked for us. So, we at least made sure that we were doing something wrong while doing bulk update.

After spending some time on this issue, we gave a try to create another instance of the same entity rather than using it directly and passed it as Target to UpdateRequest inside foreach loop as shown below(rest of the code remaining as it is) and it worked:

  foreach (var line in lines)
dxc_revenuescheduleline entity = new dxc_revenuescheduleline { Id = line.Id };
UpdateRequest updateRequest = new UpdateRequest { Target = entity };
entity.dxc_EndDate = serviceEntryDetail.dxc_DepartureDate;

Hope it helps !!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.