如何通过 C# 检索特定机会的所有机会产品?

How to retrieve all Opportunity Products for the specific Opportunity through c#?

我有机会,如下图所示:

昨天,我发布了一个关于如何创建机会产品(汽车产品)的问题,Dave 向我提供了 如何实现这一点。

现在,我的要求已扩展为删除这些现有的电机产品并添加新产品。

我想通过首先从这个机会中检索所有相关的汽车产品来做到这一点。

为了创建机会产品,我使用了以下代码:

var opportunityProduct = new Entity(entityMotorName);
opportunityProduct["tmeic_opportunitymotorproductid"] = new EntityReference("opportunity", Guid("opportunityid"));
var opportunityProductId = crmService.Create(opportunityProduct);

但是,我被困在这里是为了检索这些电机产品。获得与此机会相关的汽车产品后,我可以使用以下查询。

crmService.Delete(entityName,Guid);

注意:我的机会有 opportunityid 但没有 tmeic_opportunitymotorproductid & 我的汽车产品 (opportunityproduct) 没有 opportunityid 但有 tmeic_opportunitymotorproductid.

唯一的问题是如何检索这些电机产品?

这是一种方法:

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Linq;

class App
{
    private IOrganizationService svc;

    public App(IOrganizationService svc)
    {
        this.svc = svc;
    }

    public void Run()
    {
        var list = OppProducts(svc, new Guid("628CF01A-AED1-E411-80EF-C4346BAC7BE8"));
        DeleteList(svc, list);
    }

    public List<Entity> OppProducts(IOrganizationService svc, Guid OppId)
    {
        var query = new QueryExpression
        {
            EntityName = "opportunityproduct",
            ColumnSet = new ColumnSet("tmeic_opportunitymotorproductid", "opportunityproductid"),
            Criteria = new FilterExpression
            {
                FilterOperator = LogicalOperator.And,
                Conditions =
                {
                    new ConditionExpression
                    {
                        AttributeName = "tmeic_opportunitymotorproductid",
                        Operator = ConditionOperator.Equal,
                        Values = { OppId }
                    }   
                }
            }
        };

        var result = svc.RetrieveMultiple(query);

        return result.Entities.ToList();
    }

    public void DeleteList(IOrganizationService svc, List<Entity> list)
    {
        list.ForEach(e => svc.Delete(e.LogicalName, e.Id));
    }
}