using System;
using System.Linq;
using Telerik.OpenAccess;

namespace _1_ORM_CRUD_Operations
{
    class Program
    {
        static void Main(string[] args)
        {
            using (IObjectScope scope = ObjectScopeProvider1.ObjectScope())
            {
                scope.Transaction.Begin();

                // add a new customer
                Customer newCustomer = new Customer();
                newCustomer.CustomerID = "A" + System.DateTime.Now.ToString("hmsfff");
                newCustomer.CompanyName = "New Customer";
                scope.Add(newCustomer);
                Console.WriteLine("Added New Customer");

                // get first customer using LINQ and modify
                Customer firstCustomer =
                  scope.Extent<Customer>().Take(1).Single();
                firstCustomer.CompanyName =
                  "Company " + DateTime.Now.ToString("hmsfff");
                scope.Add(firstCustomer);
                Console.WriteLine("Modified First Customer");

                // use LINQ to retrieve customer ID's starting with "E"
                var results =
                  from c in scope.Extent<Customer>()
                  where c.CompanyName.StartsWith("E")
                  select c;
                Console.WriteLine("Retreived all customers starting with E");

                // delete "E" customers from the database
                foreach (Customer cust in results)
                {
                    foreach (Order order in cust.Orders)
                    {
                        foreach (OrderDetail detail in order.OrderDetails)
                        {
                            scope.Remove(detail);
                        }
                        scope.Remove(order);
                    }
                    scope.Remove(cust);
                }
                Console.WriteLine("Removed all customers starting with E");
                scope.Transaction.Commit();
            }

            Console.Write("Done");
            Console.ReadLine();
        }
    }
}
