Microsoft Dynamics CRM - 错误消息:实体ID必须与属性包中设置的值相同

use*_*501 3 c# microsoft-dynamics dynamics-crm dynamics-crm-2013

您好StackOverflow社区,

我只是尝试复制"联系人"的记录 - 来自插件的实体或自定义工作流活动.相关守则是

            QueryExpression qe = new QueryExpression("contact")
            {
                ColumnSet =  new ColumnSet("firstname", "lastname")
            };
            EntityCollection entityCollection = _organizationService.RetrieveMultiple(qe);
            foreach (Entity entity in entityCollection.Entities)
            {
                entity.Id = Guid.NewGuid();

                if (!entity.Attributes.Contains("firstname"))
                {
                    entity.Attributes.Add("firstname", "");
                }
                entity["firstname"] = (entity.GetAttributeValue<string>("firstname") ?? "") + "(Copy)";

                _organizationService.Create(entity);
            }
Run Code Online (Sandbox Code Playgroud)

不幸的是,我总是收到错误消息

"实体ID必须与属性包中设置的值相同".

如果我遗漏了这条线

Entity.Id = Guid.NewGuid();
Run Code Online (Sandbox Code Playgroud)

然后我收到了错误

"无法插入重复的密钥."

我还尝试了各种其他方法来构建一个新的Guid,包括

byte [] bytes = new byte[16];
random.NextBytes(bytes);
entity.Id = new Guid(bytes);
Run Code Online (Sandbox Code Playgroud)

要么

entity.Id = Guid.Empty;
Run Code Online (Sandbox Code Playgroud)

结果也是

"实体ID必须与属性包中设置的值相同".

另一方面,我有一个桌面应用程序,我借助本文https://msdn.microsoft.com/en-us/library/jj602970.aspx连接到我的Microsoft CRM 2016 Office 365系统并可以复制记录行.

任何帮助是极大的赞赏.

Dar*_*ryl 6

QueryExpression始终返回ID,既作为实际Entity.Id,和它的属性名contactid.这就是你得到错误的原因.您可以删除此属性,但最佳做法是始终创建新的C#Contact对象,而不是更新从CRM中检索的对象.此外,您不希望设置自己的GUID,因为CRM使用更好地优化索引和排序的顺序GUIDS.

QueryExpression qe = new QueryExpression("contact")
{
    ColumnSet =  new ColumnSet("firstname", "lastname")
};

foreach (Entity entity in _organizationService.RetrieveMultiple(qe).Entities)
{
    var copy = new Entity();
    copy["firstname'] = (entity.GetAttributeValue<string>("firstname") ?? "") + "(Copy)";
    _organizationService.Create(copy);
}
Run Code Online (Sandbox Code Playgroud)