"EntityState must be set to null, Created (for Create message) or Changed (for Update message)" when attempting to update an entity in CRM 2011

Neil picture Neil · May 31, 2011 · Viewed 18.6k times · Source

I am using the following code to update an entity.

Service.Update(_policy);

where policy is a class generated using CrmSvcUtil.exe

public partial class new_policy : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged

I retrieve the policies using LINQ, then update one attribute (an EntityReference) and then attempt the update

When this code runs I get the following error message:

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

There are other entities generated in the same way that I can update.

I tried

_policy.EntityState = EntityState.Changed

but then I get a message saying

The entity is read-only and the 'EntityState' property cannot be modified. Use the context to update the entity instead.

Does anyone know what is causing this?

Answer

ccellar picture ccellar · May 31, 2011

You have to tell your crmContext (use appropriate name) what to do with the changes.

You should add crmContext.UpdateObject(contact); before crmContext.SaveChanges();

See also How to update a CRM 2011 Entity using LINQ in a Plugin?