protected void CreatePriceListItem(string opportunityId, Guid productId, Guid unitId, Money materialCost) { var fetchDataOpportunity = new { PriceLevelopportunityid = opportunityId }; var PriceLevelFetch = $@" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='pricelevel'> <attribute name='transactioncurrencyid' /> <attribute name='name' /> <attribute name='pricelevelid' /> <link-entity name='opportunity' from='pricelevelid' to='pricelevelid'> <filter type='and'> <condition attribute='opportunityid' operator='eq' value='{fetchDataOpportunity.PriceLevelopportunityid}'/> </filter> </link-entity> </entity> </fetch>"; EntityCollection priceLevelData = service.RetrieveMultiple(new FetchExpression(PriceLevelFetch)); foreach (var priceLevel in priceLevelData.Entities) { var productPriceLevelData = new { productid = productId }; var productPriceLevelfetchXml = $@" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='productpricelevel'> <attribute name='productid' /> <attribute name='pricelevelid' /> <attribute name='productpricelevelid' /> <attribute name='productidname' /> <filter type='and'> <condition attribute='productid' operator='eq' value='{productPriceLevelData.productid}'/> </filter> </entity> </fetch>"; var check = true; var productPriceLevelId = new Guid(); EntityCollection productPriceLevel = service.RetrieveMultiple(new FetchExpression(productPriceLevelfetchXml)); foreach (var product in productPriceLevel.Entities) { var proId = (EntityReference)(product.Attributes["productid"]); if (proId.Id.Equals(productId) && !productPriceLevel.Equals(null)) { check = false; productPriceLevelId = (Guid)product.Attributes["productpricelevelid"]; } } var priceList = priceLevel.Attributes["pricelevelid"]; if (check) { Entity priceListItem = new Entity("productpricelevel"); priceListItem["pricelevelid"] = new EntityReference("pricelevel", (Guid)priceList); priceListItem["productid"] = new EntityReference("product", productId); priceListItem["uomid"] = new EntityReference("uom", unitId); priceListItem["amount"] = materialCost; service.Create(priceListItem); } else { Entity priceListItem = service.Retrieve("productpricelevel", productPriceLevelId, new ColumnSet("pricelevelid", "productid", "uomid", "amount")); priceListItem["pricelevelid"] = new EntityReference("pricelevel", (Guid)priceList); priceListItem["productid"] = new EntityReference("product", productId); priceListItem["uomid"] = new EntityReference("uom", unitId); priceListItem["amount"] = materialCost; service.Update(priceListItem); } } }