1

我正在使用 CRM 版本 9.0,我想通过 C# 删除 CRM 中具有相同 ID 的所有记录。

我想实现这样的事情(我给出一个 SQL 查询示例仅供参考)

Delete from entityName where id = @id

目前,我正在使用下面的 C# 代码在 CRM 中创建记录

dictionary.Add("code", new CrmDataTypeWrapper(code, CrmFieldType.Raw));
dictionary.Add("id", new CrmDataTypeWrapper(id, CrmFieldType.Raw));
Guid EvntId = _client.CrmInterface.CreateNewRecord("entityname", dictionary, "", false, new System.Guid());

现在我想在这个逻辑之前编写一个代码块,如果它们存在传递的 ID,它将删除所有记录。

4

3 回答 3

0

To compliment Adriani6 answer:

I think you are trying to delete a set of records which are having particular field value. But that field is named as id which is not a primary key.

There is no equivalent of the below SQL query in Dynamics CRM.

Delete from entityName where id = @id

You have to fetch all the entity records matching this condition of non-primary key using service.RetrieveMultiple and then iterate through the result set for each record to issue service.Delete request with primary key.

QueryExpression query = new QueryExpression("entityName");
query.ColumnSet = new ColumnSet(new string[] { "eventId", "code"});
query.Criteria.AddCondition(new ConditionExpression("id", ConditionOperator.Equal, id));

EntityCollection events = service.RetrieveMultiple(query);

foreach (var event in events.Entities)
{
    service.Delete("entityName", event.Id);
}
于 2019-04-06T16:19:29.633 回答
0

如果您不确定 Dynamics 中是否存在这些 id,您应该尝试捕获您的 Delete 尝试,因为如果您尝试删除 Dynamics 中不存在的记录,Dynamics 会给您一个FaultException.

var ids = new Collection<Guid>();
foreach (var id in ids)
{
    try
    {
        _service.Delete("[entityName]", id);
    }
    catch (FaultException)
    {
        continue;
    }
}
于 2019-04-05T11:09:04.370 回答
0

为了删除 CRM 中的实体 - 您必须首先获取实体以获取GUID实体的。

IOrganizationService接口包含一个Delete方法,该方法需要实体类型 ( LogicalName) 和 CRM 创建的实体的 GUID。

这是我们如何做到的。

QueryExpression oppQuery = new QueryExpression("opportunity");
oppQuery.ColumnSet = new ColumnSet(new string[] { "opportunityid" });
oppQuery.Criteria.AddCondition(new ConditionExpression("parentcontactid", ConditionOperator.Equal, contact.Id));

EntityCollection opportunities = crmSvc.RetrieveMultiple(oppQuery);

foreach (var opportunity in opportunities.Entities)
{
    service.Delete("opportunity", opportunity.Id);
}

这意味着您可以通过根据您的条件首先获取您需要的实体来根据您的条件删除实体。

oppQuery.Criteria.AddCondition(new ConditionExpression("<your id field>", ConditionOperator.Equal, <your id>));

在此行中,您指定用于删除相关实体的条件。

于 2019-04-05T08:28:56.477 回答