在 CRM 2011 C# 中更新记录时避免重复

Avoid duplicates when updating records in CRM 2011 C#

我编写了从 CRM 检索记录并更新此记录的应用程序。 但是当我 运行 和 "service.Update(...)" 时,记录是重复的(我在 SQL 服务器数据库中看到了它)。 我只想从特定的 Guid 获得一条记录,现在我有 2 条。

            foreach (DataRow row in rsltFromSql.Rows)
            {
                ActivityMimeAttachment attachmentMimeTemp = new ActivityMimeAttachment();
                try
                {
                    attachmentMimeTemp = (ActivityMimeAttachment)handlerCrm.CrmService.Retrieve(ActivityMimeAttachment.EntityLogicalName, Guid.Parse(row["ActivityMimeAttachmentId"].ToString()), new ColumnSet(true));
                }
                catch (Exception ex)
                {
                    /////
                }

                //delete body field
                attachmentMimeTemp.Body = null;

                //update the attachment with body = null
                handlerCrm.CrmService.Update(attachmentMimeTemp);

                attachmentMimeGuidList.Add(new Guid(row["ActivityMimeAttachmentId"].ToString()));
            }

不是创建 ActivityMimeAttachment 的新对象实例,而是直接从 Retrieve 方法为其分配 return 值。像这样:

foreach (DataRow row in rsltFromSql.Rows)
{
    ActivityMimeAttachment attachmentMimeTemp;
    try
    {
        attachmentMimeTemp = (ActivityMimeAttachment)handlerCrm.CrmService.Retrieve(ActivityMimeAttachment.EntityLogicalName, Guid.Parse(row["ActivityMimeAttachmentId"].ToString()), new ColumnSet(true));
    }
    catch (Exception ex)
    {
         /////
    }

    //delete body field
    attachmentMimeTemp.Body = null;

    //update the attachment with body = null
    handlerCrm.CrmService.Update(attachmentMimeTemp);

    attachmentMimeGuidList.Add(new Guid(row["ActivityMimeAttachmentId"].ToString()));
}

删除 activityMimeAttachment 并创建一个新的:

            //Retrieve ActivityMimeAttachment
            ActivityMimeAttachment attachmentMimeTemp;

            attachmentMimeTemp = (ActivityMimeAttachment)handlerCrm.CrmService.Retrieve(ActivityMimeAttachment.EntityLogicalName, Guid.Parse(row["ActivityMimeAttachmentId"].ToString()), new ColumnSet(true));

            //delete the old attachment (kit)
            handlerCrm.CrmService.Delete(ActivityMimeAttachment.EntityLogicalName, attachmentMimeTemp.Id);

            //create new attachment to the Email
            ActivityMimeAttachment newAttachment = new ActivityMimeAttachment
            {
                ObjectId = attachmentMimeTemp.ObjectId,
                ObjectTypeCode = "email",
                Body = System.Convert.ToBase64String(
                                new ASCIIEncoding().GetBytes("Example Attachment")),
                FileName = String.Format("newFile")
            };
            handlerCrm.CrmService.Create(newAttachment);