using System.Linq;
using System.Data.Services.Client;

namespace SilverlightApplication1.ServiceReference1
{
    public partial class Customer
    {
        public Customer()
        {
            _Orders = null;
        }

        internal NorthwindEntities Context { get; set; }

        public DataServiceCollection<Order> OrdersCollection
        {
            get
            {
                if (_Orders == null && Context != null)
                {
                    _Orders = new DataServiceCollection<Order>(Context);
                    _Orders.CollectionChanged += (s, e) =>
                    {
                        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                        {
                            foreach (var c in e.NewItems.OfType<Order>())
                            {
                                c.Context = this.Context;
                            }
                        }
                        else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
                        {
                            foreach (var c in e.OldItems.OfType<Order>())
                            {
                                c.Context = null;
                            }
                        }
                    };
                    _Orders.LoadAsync(from o in Context.Orders
                                      where o.CustomerID == CustomerID
                                      select o);
                }
                return _Orders;
            }
        }
    }
}
