“尝试更新CRM 2011中的实体时,必须将EntityState设置为null,Created(对于Create消息)或Changed(对于Update message)”

时间:2011-05-31 13:02:49

标签: dynamics-crm-2011

我使用以下代码更新实体。

Service.Update(_policy);

其中policy是使用CrmSvcUtil.exe生成的类

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

我使用LINQ检索策略,然后更新一个属性(EntityReference),然后尝试更新

当此代码运行时,我收到以下错误消息:

  

EntityState必须设置为null,Created(用于创建消息)或   已更改(对于更新消息)

还有其他实体以我可以更新的相同方式生成。

我试过

_policy.EntityState = EntityState.Changed

然后我收到一条消息说

  

实体是只读的,'EntityState'属性不可以   改性。请使用上下文来更新实体。

有谁知道造成这种情况的原因是什么?

5 个答案:

答案 0 :(得分:20)

您必须告诉您的crmContext(使用适当的名称)如何处理更改。

  

你应该添加crmContext.UpdateObject(contact);在crmContext.SaveChanges();

之前

另见How to update a CRM 2011 Entity using LINQ in a Plugin?

答案 1 :(得分:9)

我遇到了同样的问题。我改用了

context.Update(object) 

context.UpdateObject(object) 

它有效。

答案 2 :(得分:8)

要避免此问题,您只需使用update-helper-objects而不是使用检索到的记录:

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

注意:将忽略未设置的update-helper-object的属性。更新不会将相应的记录字段设置为null

答案 3 :(得分:2)

这对我有用:

recordToUpdate.EntityState = EntityState.Changed;

(recordToUpdate是要更新的实体)

答案 4 :(得分:1)

事实证明,我的linq查询首先检索实体是一个问题。当我用查询表达式替换它时,它工作正常。

时间刷新我的linq了!