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

China☆狼群 提交于 2019-12-18 05:37:44

问题


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?


回答1:


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?




回答2:


I had the same problem. I switched from using

context.Update(object) 

to

context.UpdateObject(object) 

and it worked.




回答3:


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




回答4:


This worked for me:

recordToUpdate.EntityState = EntityState.Changed;

(recordToUpdate is an Entity to be updated)




回答5:


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!



来源:https://stackoverflow.com/questions/6187978/entitystate-must-be-set-to-null-created-for-create-message-or-changed-for-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!