Hello,
Please could someone help me with the syntax to add orderlines to an order in the below? I just cant figure out the syntax for it.
many thanks

using System;
using System.Collections.Generic;

namespace ParentChild
{
    class Program
    {
        static void Main(string[] args)
        {
            var Order = new Order { Id = 1,
                Description = "My First Order",
                OrderDate = DateTime.Now,
                OrderLines.Add(new OrderLine { OrderId =1, Quantity = 100}) //**How do i add orderlines here?**
            };
        }
    }
    public class Order
    {
        public Order()
        {
            OrderLines = new List<OrderLine>();
        }
        public int Id { get; set; }
        public DateTime OrderDate { get; set; }
        public string Description { get; set; }
        public virtual List<OrderLine> OrderLines { get; set; }
    }
    public class OrderLine
    {
        public int OrderId { get; set; }
        public int Quantity { get; set; }
        public virtual Order Order { get; set; }
    }
}

Recommended Answers

All 2 Replies

One way is to use a public method that uses the Add method of the List class:

void AddOrderLine(OrderLine newOrderLine)
{
    OrderLines.Add(newOrderLine)
}

I would suggest keeping the list private instead of public. This way you choose which methods the user can use to interact with the list and eliminates the possibility of using a method that interferes with your goals.

As for adding more lines that would depend on how you are receiving the data. Normally a while loop works very well for this.

Hi,
thanks, but i needed syntax to do it by using an Object Initialiser. I managed to work it out as below but i found the issue is that object initialisers do not call the constructor - where i initialised the list :

        var order = new Order { Id = 1,
            Description = "My First Order", 
            OrderDate = DateTime.Now,
            OrderLines = new List<OrderLine>() {
                new OrderLine { OrderLineId =1, Quantity = 100 },
                new OrderLine { OrderLineId =2, Quantity = 200 },
                new OrderLine { OrderLineId =3, Quantity = 300 }
            }
        };
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.