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

时间:2015-04-06 08:23:43

标签: c# sql-server dynamics-crm-2011 crm

我编写了从CRM检索记录并更新此记录的应用程序。 但是当我运行“service.Update(...)”时,记录是重复的(我在SQL Server数据库中看到它)。 我想只有一个来自特定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()));
            }

2 个答案:

答案 0 :(得分:0)

而不是创建ActivityMimeAttachment的新对象实例,只需直接从Retrieve方法指定返回值即可。像这样:

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

答案 1 :(得分:0)

删除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);