Link to home
Start Free TrialLog in
Avatar of pink glitter
pink glitter

asked on

Adding items in order gives NullReferenceException (WooCommerce, in C# and using WooCommerce.NET addin.

I am trying to use this code for making an order in Woocommerce, using this add-on :https://github.com/XiaoFaye/WooCommerce.NET. My code is this:  

        var order = new Order() { status = "pending" };
        order.currency = "EUR";
        order.line_items.Add(new OrderLineItem()
        {
            id=44,
            product_id = 44,
            quantity=2
        }
          );
        order.customer_id = 1;
 
       Task ord = wc.Order.Add(order);
       ord.Wait();
But everytime it gives me this exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'

I have tried everything but no success...
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

You haven't said which line gives you the error, so I'm going to guess that it's either line 3 (order.line_items.Add) or 12 (Task ord = wc.Order.Add(order);

Both of these lines look like they're adding an object to list, so it's possible that the list itself hasn't been initialised:

order.line_items = new List<OrderLineItem>();
order.line_items.Add(new OrderLineItem()
   ...

Open in new window

Avatar of pink glitter
pink glitter

ASKER

@Chris Stanyon
Hello and thanks for answering! Sorry that i didn't mention it... The line in question is this

order.line_items.Add(new OrderLineItem()
        {
            id=44,
            product_id = 44,
            quantity=2
        }
          );

Thanks again!
On which line you get this exception? Is it when you try to add Products?
order.line_items.Add(new OrderLineItem()

Open in new window


Maybe you would want to first initialize line_items?

i.e.

order.line_items = new line_items()

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It depends on what your collection type is but, you could do something like this:
var order = new Order { status = "pending" };
order.currency = "EUR";
order.line_items = new List<OrderLineItem>() { new OrderLineItem { id = 44, product_id = 44, quantity = 2 } };
order.customer_id = 1;

Open in new window

-saige-