Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 865
Neil Avatar asked May 31 '11 13:05

Neil


5 Answers

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?

like image 154
ccellar Avatar answered Nov 08 '22 23:11

ccellar


To avoid the problem you can simply use update-helper-objects instead of using the retrieved record:

var policyUpdater = new Policy { Id = _policy.Id, FieldToUpdate = "newValue" };
service.Update(policyUpdater);

Note: Properties of the update-helper-object that aren't set are simply ignored. The update won't set the corresponding record fields to null

like image 22
user764754 Avatar answered Nov 08 '22 23:11

user764754


I had the same problem. I switched from using

context.Update(object) 

to

context.UpdateObject(object) 

and it worked.

like image 10
KClough Avatar answered Nov 08 '22 23:11

KClough


This worked for me:

recordToUpdate.EntityState = EntityState.Changed;

(recordToUpdate is an Entity to be updated)

like image 2
Charan Raju C R Avatar answered Nov 08 '22 23:11

Charan Raju C R


Turns out it was an issue with my linq query that was retrieving the entity in the first place. When I replaced this with a query expression it worked okay.

Time to brush up on my linq!

like image 1
Neil Avatar answered Nov 09 '22 00:11

Neil