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

Microsoft Dynamics CRM - Error message: Entity Id must be the same as the value set in property bag

嗨,Whosebug 社区,

我只是尝试从插件或自定义工作流程中复制 "contact"- 实体的记录 activity。 相关代码为

            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);
            }

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

"Entity Id must be the same as the value set in property bag".

如果我省略了这一行

Entity.Id = Guid.NewGuid();

然后我收到错误

"Cannot insert duplicate key."

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

byte [] bytes = new byte[16];
random.NextBytes(bytes);
entity.Id = new Guid(bytes);

entity.Id = Guid.Empty;

也导致

"Entity Id must be the same as the value set in property bag".

另一方面,我有一个桌面应用程序,在这篇文章的帮助下我可以连接到我的 Microsoft CRM 2016 Office 365 系统 https://msdn.microsoft.com/en-us/library/jj602970.aspx 并且可以正常复制记录。

非常感谢任何帮助。

QueryExpression 总是 returns id,既是实际的 Entity.Id,也是 属性 名称 contactid。这就是您收到错误的原因。您可以只删除此属性,但最佳做法是始终创建一个新的 C# 联系人对象,而不是更新从 CRM 检索到的对象。此外,您不希望设置自己的 GUID,因为 CRM 使用顺序 GUID,这些 GUID 针对索引和排序进行了更好的优化。

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);
}