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

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.

Edited 10 Months Ago by tinstaafl

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 }
            }
        };
This question has already been answered. Start a new discussion instead.