Search code examples
c#.net.net-coredynamics-crmxrm

Adding sales order details to sales order in dynamics crm


I am working to create a sales order with a single product added to the sales order detail and attach that to the sales order.

It is throwing me an error and I am wondering if there is a proper way to performing this action?

Thanks!

 public void  Create(CrmContextCore _crmContext, Guid productId, UserEntityModel currentuser)
{
    var detail = new Entity("salesorderdetail");
    {

        detail["productid"] = new EntityReference("product", productId);
    }

    var salesorder = new Entity("salesorder");
    {
        salesorder["accountid"] = new EntityReference("account", currentuser.AccountId);
        salesorder["contactid"] = new EntityReference("contact", currentuser.ContactId );
        salesorder["emailaddress"] = currentuser.Email;
        salesorder["name"] = "DealerPO123";
        salesorder["salesorderdetail"] = detail;

    }

    _crmContext.ServiceContext.AddObject(salesorder);

    _crmContext.ServiceContext.SaveChanges();

}

Solution

  • Sample: Set negative prices in opportunities, quotes, and sales orders.

    // Create the sales order.
    SalesOrder order = new SalesOrder()
    {
        Name = "Faux Order",
        DateFulfilled = new DateTime(2010, 8, 1),
        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
            _priceListId),
        CustomerId = new EntityReference(Account.EntityLogicalName,
            _accountId),
        FreightAmount = new Money(20.0M)
    };
    _orderId = _serviceProxy.Create(order);
    order.Id = _orderId;
    
    // Add the product to the order with the price overriden with a
    // negative value.
    SalesOrderDetail orderDetail = new SalesOrderDetail()
    {
        ProductId = new EntityReference(Product.EntityLogicalName, 
            _product1Id),
        Quantity = 4,
        SalesOrderId = order.ToEntityReference(),
        IsPriceOverridden = true,
        PricePerUnit = new Money(-40.0M),
        UoMId = new EntityReference(UoM.EntityLogicalName, 
            _defaultUnitId)
    };
    _orderDetailId = _serviceProxy.Create(orderDetail);