Dynamics crm Dynamics CRM保存实体更改-获取错误

Dynamics crm Dynamics CRM保存实体更改-获取错误,dynamics-crm,dynamics-crm-2011,Dynamics Crm,Dynamics Crm 2011,这真让我抓狂。我正在尝试使用Dynamics CRM SDK更新帐户记录。不管我怎么尝试,都是失败的。来吧 Account sampleAccount = CrmAccount.GetAccountsBySubmissionCode(crmService, "ERZZUP").Single<Account>(); sampleAccount.Name = "AMC Edited"; crmService.Update(sampleAccount); Account sampleAc

这真让我抓狂。我正在尝试使用Dynamics CRM SDK更新帐户记录。不管我怎么尝试,都是失败的。来吧

Account sampleAccount = CrmAccount.GetAccountsBySubmissionCode(crmService, "ERZZUP").Single<Account>();
sampleAccount.Name = "AMC Edited";
crmService.Update(sampleAccount);
Account sampleAccount=CrmAccount.GetAccountsBySubmissionCode(crmService,“ERZZUP”).Single();
sampleAccount.Name=“AMC已编辑”;
crmService.Update(sampleAccount);
给出错误:EntityState必须设置为null、已创建(用于创建消息)或已更改(用于更新消息)

XrmServiceContext ctx=新的XrmServiceContext(crmService);
Account sampleAccount=CrmAccount.GetAccountsBySubmissionCode(crmService,“ERZZUP”).Single();
sampleAccount.Name=“AMC已编辑”;
ctx.UpdateObject(sampleAccount);
ctx.SaveChanges();
给出错误:上下文当前未跟踪“帐户”实体

XrmServiceContext ctx=新的XrmServiceContext(crmService);
Account sampleAccount=CrmAccount.GetAccountsBySubmissionCode(crmService,“ERZZUP”).Single();
sampleAccount.Name=“AMC已编辑”;
ctx.附件(样本账户);
ctx.UpdateObject(sampleAccount);
ctx.SaveChanges();
给出错误:“帐户”实体已附加到上下文

作为参考, 1.Account对象由SDK早期绑定代码生成工具创建 2.crmService是IOOrganizationService连接对象 3.获取帐户。。。执行LINQ查询并返回IEnumerable

请帮忙。 谢谢 Chris.

请参阅,尤其是“多数据上下文”部分。您似乎正在使用多个上下文来跟踪实体。
CrmAccount.GetAccountsBySubmissionCode方法只是对您隐藏这一点


在返回
IEnumerable
之前,请确保在
CrmAccount.GetAccountsBySubmissionCode方法中处理上下文/服务,或者确保使用相同的上下文/服务来
更新

您认为GetAccounts中存在上下文是正确的。。。。方法。但是,我现在在返回IEnumerable之前在上下文中调用Dispose(),仍然会得到错误。Ok。一直在玩更多和移动LINQ修复它。我将重新构造我的方法,以便在现有上下文中传递以供使用。感谢您的指针,它真的很有帮助。处理上下文的一种更健壮的方法是使用
使用(var context=new XrmServiceContext()){//code}
块。在using块之前声明IEnumerable,在using块中分配结果,然后返回结果。另一种方法是将
CrmAccount.GetAccountsBySubmissionCode
设置为静态,并将上下文/服务作为参数提供给它。这样你就完全可以确定上下文是一样的。
XrmServiceContext ctx = new XrmServiceContext(crmService);
Account sampleAccount = CrmAccount.GetAccountsBySubmissionCode(crmService, "ERZZUP").Single<Account>();
sampleAccount.Name = "AMC Edited";
ctx.UpdateObject(sampleAccount);
ctx.SaveChanges();
XrmServiceContext ctx = new XrmServiceContext(crmService);
Account sampleAccount = CrmAccount.GetAccountsBySubmissionCode(crmService, "ERZZUP").Single<Account>();
sampleAccount.Name = "AMC Edited";
ctx.Attach(sampleAccount);
ctx.UpdateObject(sampleAccount);
ctx.SaveChanges();