Search code examples
c#dynamics-crmdynamics-crm-online

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


I have the Opportunity as shown in the below image:

Opportunity with sub items

Yesterday, I posted a question on how to create the Opportunity Products (Motor Products) & Dave provided me an answer on how to achieve this.

Now, my requirement has been extended to delete these existing Motor Products & add new products.

I'm thinking to do this by first retrieving all the relative Motor Products from this opportunity.

For creating Opportunity Product I used the below code:

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

But, I'm stuck here for retrieing these Motor Products. Once I get the Motor Products which is related to this opportunity I can use the below query.

crmService.Delete(entityName,Guid);

Note: my opportunity has opportunityid but no tmeic_opportunitymotorproductid & my Motor Product (opportunityproduct) doesn't have opportunityid but has tmeic_opportunitymotorproductid.

Only problem is how to retrieve these Motor Products?


Solution

  • Here's one way to do this:

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