Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            // <Snippet1>
            // Create a new Order object.
            Order ord = new Order
            {
                OrderID   = 12000,
                ShipCity  = "Seattle",
                OrderDate = DateTime.Now
                            // …
            };

            // Add the new object to the Orders collection.
            db.Orders.InsertOnSubmit(ord);

            // Submit the change to the database.
            try
            {
                db.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // Make some adjustments.
                // ...
                // Try again.
                db.SubmitChanges();
            }
            // </Snippet1>
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            // <Snippet1>
            Northwnd db = new Northwnd("...");

            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }

            catch (ChangeConflictException e)
            {
                Console.WriteLine(e.Message);
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    // All database values overwrite current values.
                    occ.Resolve(RefreshMode.OverwriteCurrentValues);
                }
            }
            // </Snippet1>

            // <Snippet2>
            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }

            catch (ChangeConflictException e)
            {
                Console.WriteLine(e.Message);
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    //No database values are merged into current.
                    occ.Resolve(RefreshMode.KeepCurrentValues);
                }
            }
            // </Snippet2>

            // <Snippet3>
            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }

            catch (ChangeConflictException e)
            {
                Console.WriteLine(e.Message);
                // Automerge database values for members that client
                // has not modified.
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    occ.Resolve(RefreshMode.KeepChanges);
                }
            }

            // Submit succeeds on second try.
            db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            // </Snippet3>
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            // <Snippet1>
            Northwnd db = new Northwnd("...");

            // Create, update, delete code.

            db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            // or
            db.SubmitChanges(ConflictMode.ContinueOnConflict);
            // </Snippet1>
        }
Ejemplo n.º 4
0
        void methodDelete()
        {
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

// <Snippet3>
// Query the database for the rows to be deleted.
            var deleteOrderDetails =
                from details in db.OrderDetails
                where details.OrderID == 11000
                select details;

            foreach (var detail in deleteOrderDetails)
            {
                db.OrderDetails.DeleteOnSubmit(detail);
            }

            try
            {
                db.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // Provide for exceptions.
            }
// </Snippet3>
        }
Ejemplo n.º 5
0
        void methodUpdate()
        {
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            // <Snippet2>
            // Query the database for the row to be updated.
            var query =
                from ord in db.Orders
                where ord.OrderID == 11000
                select ord;

            // Execute the query, and change the column values
            // you want to change.
            foreach (Order ord in query)
            {
                ord.ShipName = "Mariner";
                ord.ShipVia  = 2;
                // Insert any additional changes to column values.
            }

            // Submit the changes to the database.
            try
            {
                db.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // Provide for exceptions.
            }
            // </Snippet2>
        }
Ejemplo n.º 6
0
        void method2()
        {
            // <Snippet2>
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            var custQuery =
                from cust in db.Customers
                where cust.City == "London"
                select cust;

            foreach (Customer custObj in custQuery)
            {
                Console.WriteLine("CustomerID: {0}", custObj.CustomerID);
                Console.WriteLine("\tOriginal value: {0}", custObj.City);
                custObj.City = "Paris";
                Console.WriteLine("\tUpdated value: {0}", custObj.City);
            }

            ChangeSet cs = db.GetChangeSet();

            Console.Write("Total changes: {0}", cs);
            // Freeze the console window.
            Console.ReadLine();

            db.SubmitChanges();
            // </Snippet2>
        }
Ejemplo n.º 7
0
        void method3()
        {
            // <Snippet3>
            Customer CustA_File = new Customer();
            Customer CustB_File = new Customer();
            string   xmlFileA   = "";
            string   xmlFileB   = "";

            // Get the serialized objects.
            Customer     A       = SerializeHelper.Deserialize <Customer>(xmlFileA, CustA_File);
            Customer     B       = SerializeHelper.Deserialize <Customer>(xmlFileB, CustB_File);
            List <Order> AOrders = A.Orders.ToList();

            using (Northwnd db = new Northwnd(@"c:\northwnd.mdf"))

            {
                //Attach all the orders belonging to Customer A all at once.
                db.Orders.AttachAll(AOrders, false);

                // Update the orders belonging to Customer A to show them
                // as owned by Customer B.
                foreach (Order o in AOrders)
                {
                    o.CustomerID = B.CustomerID;
                }

                // DataContext can now apply the change of ownership to
                // the database.
                db.SubmitChanges();
            }
            // </Snippet3>
        }
Ejemplo n.º 8
0
        void method4()
        {
            // <Snippet4>
            using (Northwnd db2 = new Northwnd(@"c:\northwnd.mdf"))
            {
                Customer Cust_File = new Customer();
                string   xmlFile   = "";

                // Get the original object from the deserializer.
                Customer c = SerializeHelper.Deserialize <Customer>
                                 (xmlFile, Cust_File);

                // Set all the desired properties to the entity to be attached.
                Customer c_updated = new Customer()
                {
                    CustomerID = c.CustomerID,
                    Phone      = "425-123-4567", CompanyName = "Microsoft"
                };
                db2.Customers.Attach(c_updated, c);

                // Perform last minute updates, which will still take effect.
                c_updated.Phone = "425-765-4321";

                // SubmitChanges()sets the phoneNumber and CompanyName of
                // customer with customerID=Cust. to "425-765-4321" and
                // "Microsoft" respectively.
                db2.SubmitChanges();
            }
            // </Snippet4>
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            // <Snippet1>
            Northwnd db = new Northwnd(@"c:\Northwnd.mdf");

            // Query for a specific customer.
            var cust =
                (from c in db.Customers
                 where c.CustomerID == "ALFKI"
                 select c).First();

            // Change the name of the contact.
            cust.ContactName = "New Contact";

            // Create and add a new Order to the Orders collection.
            Order ord = new Order {
                OrderDate = DateTime.Now
            };

            cust.Orders.Add(ord);

            // Delete an existing Order.
            Order ord0 = cust.Orders[0];

            // Removing it from the table also removes it from the Customer’s list.
            db.Orders.DeleteOnSubmit(ord0);

            // Ask the DataContext to save all the changes.
            db.SubmitChanges();
            // </Snippet1>
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            // <Snippet1>
            Northwnd db = new Northwnd("...");

            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }

            catch (ChangeConflictException e)
            {
                Console.WriteLine("Optimistic concurrency error.");
                Console.WriteLine(e.Message);
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    MetaTable metatable        = db.Mapping.GetTable(occ.Object.GetType());
                    Customer  entityInConflict = (Customer)occ.Object;
                    Console.WriteLine("Table name: {0}", metatable.TableName);
                    Console.Write("Customer ID: ");
                    Console.WriteLine(entityInConflict.CustomerID);
                    Console.ReadLine();
                }
            }
            // </Snippet1>
        }
Ejemplo n.º 11
0
        // s5 is skipped


        //void method6()
        //{
        //    // s6: skip until it compiles

        //    // This tier uses DataLoadOptions to disable deferred loading. Only the
        //    // customer and orders are moved in a single serialization.

        //    DataLoadOptions shape = new DataLoadOptions();
        //    shape.LoadWith<Customer>(c => c.Orders);
        //    shape.AssociateWith<Customer>
        //        (c => c.Orders.Where(o => o.OrderDate.Year = 2007));

        //    using (Northwnd db1 = new Northwnd(@"c:\northwnd.mdf"))
        //    {
        //        Northwnd db = new Northwnd("");

        //        Customer cust = db1.Customers.First(x => x.CustomerID == "ALKFI");
        //        Order ordA = cust.Orders.First();
        //        Order ordB = cust.Orders.First(x => x.OrderID > ordA.OrderID);
        //        /* Customer cust and its Orders ord1 and ord2 are serialized here
        //        and transported over the wire or to another tier.*/

        //        db1LoadOptions = shape;
        //        db.DeferredLoadingEnabled = false;

        //        Customer cust = db1.Customers.First(x => x.CustomerID == "ALKFI");
        //        SerializeHelper.Serialize(cust, xmlFile);

        //    }

        //    // The following is a different tier using a different DataContext.
        //    using (Northwnd db2 = new Northwnd(@"c:\northwnd.mdf"))
        //    {
        //        // cust, ord1 and ord2 are deserialized here.
        //        Customer cust = (Customer)
        //            SerializeHelper.Deserialize<Customer>(xmlFile);
        //        Order orderA = cust.Orders.First();
        //        Order orderB = cust.Orders.First(x => x.OrderID > ordA.OrderID);

        //        // Create a new Order to be added to Customer cust.
        //        Order orderC = new Order()
        //        {
        //            OrderID = 12345,
        //            CustomerID =
        //                cust.CustomerID
        //        };

        //        /* Attach the customers and the Orders so that IdentityTracker and
        //        ChangeTracker are aware of these entity objects.*/
        //        db2.Customers.Attach(cust, false);
        //        db2.Orders.AttachAll(cust.Orders.ToList());

        //        /* Perform the modifications on the objects. Specifically,
        //        update customer, update order A, remove order B,
        //        and Add order C.*/
        //        cust.Phone = "2345 5436";
        //        orderA.ShipCity = "redmond";
        //        cust.Orders.DeleteOnSubmit(orderB);
        //        cust.Orders.InsertOnSubmit(orderC);

        //        // Submit all the changes.
        //        db2.SubmitChanges();
        //    }

        //}

        void method7()
        {
            // <Snippet7>
            Customer c = null;

            using (Northwnd db = new Northwnd(""))
            {
                /* Get both the customer c and the customer's order
                 * into the cache. */
                c = db.Customers.First();
                string sc = c.Orders.First().ShipCity;
            }

            using (Northwnd nw2 = new Northwnd(""))
            {
                // Attach customers and update the address.
                nw2.Customers.Attach(c, false);
                c.Address = "new";
                nw2.Log   = Console.Out;

                /* At SubmitChanges, you will see INSERT requests for all
                 * Customer c’s orders. */
                nw2.SubmitChanges();
            }
            // </Snippet7>
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            // Use the following connection string.
            Northwnd db = new Northwnd(@"c:\linqtest5\northwnd.mdf");
            // Create the new Customer object.
            Customer newCust = new Customer();

            newCust.CompanyName = "AdventureWorks Cafe";
            newCust.CustomerID  = "ADVCA";

            // Add the customer to the Customers table.
            db.Customers.InsertOnSubmit(newCust);

            Console.WriteLine("\nCustomers matching CA before insert");

            foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("CA")))
            {
                Console.WriteLine("{0}, {1}, {2}",
                                  c.CustomerID, c.CompanyName, c.Orders.Count);
            }

            // Query for specific customer.
            // First() returns one object rather than a collection.
            var existingCust =
                (from c in db.Customers
                 where c.CustomerID == "ALFKI"
                 select c)
                .First();

            // Change the contact name of the customer.
            existingCust.ContactName = "New Contact";

            // Access the first element in the Orders collection.
            Order ord0 = existingCust.Orders[0];

            // Access the first element in the OrderDetails collection.
            OrderDetail detail0 = ord0.OrderDetails[0];

            // Display the order to be deleted.
            Console.WriteLine
                ("The Order Detail to be deleted is: OrderID = {0}, ProductID = {1}",
                detail0.OrderID, detail0.ProductID);

            // Mark the Order Detail row for deletion from the database.
            db.OrderDetails.DeleteOnSubmit(detail0);
            db.SubmitChanges();
            Console.WriteLine("\nCustomers matching CA after update");
            foreach (var c in db.Customers.Where(cust =>
                                                 cust.CustomerID.Contains("CA")))
            {
                Console.WriteLine("{0}, {1}, {2}",
                                  c.CustomerID, c.CompanyName, c.Orders.Count);
            }

            // Keep the console window open after activity stops.
            Console.ReadLine();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            // <Snippet1>
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            // Make changes here.
            try
            {
                db.SubmitChanges();
            }
            catch (ChangeConflictException e)
            {
                Console.WriteLine(e.Message);
                // Make some adjustments.
                // ...
                // Try again.
                db.SubmitChanges();
            }
            // </Snippet1>
        }
Ejemplo n.º 14
0
        static void m3()
        {
            // Create the new Customer object.
            Customer newCust = new Customer();

            newCust.CompanyName = "AdventureWorks Cafe";
            newCust.CustomerID  = "ADVCA";
            newCust.PostalCode  = "55555";
            newCust.Phone       = "555-555-5555";

            // Add the customer to the Customers table.
            db.Customers.InsertOnSubmit(newCust);
            db.SubmitChanges();

            foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("CA")))
            {
                Console.WriteLine("{0}, {1}, {2}",
                                  c.CustomerID, c.CompanyName, c.Orders.Count);
            }
        }
Ejemplo n.º 15
0
        void method2()
        {
            // <Snippet2>
            // using System.Reflection;
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            Customer newCust = new Customer();

            newCust.City        = "Auburn";
            newCust.CustomerID  = "AUBUR";
            newCust.CompanyName = "AubCo";
            db.Customers.InsertOnSubmit(newCust);

            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
            catch (ChangeConflictException e)
            {
                Console.WriteLine("Optimistic concurrency error.");
                Console.WriteLine(e.Message);
                Console.ReadLine();
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    MetaTable metatable        = db.Mapping.GetTable(occ.Object.GetType());
                    Customer  entityInConflict = (Customer)occ.Object;
                    Console.WriteLine("Table name: {0}", metatable.TableName);
                    Console.Write("Customer ID: ");
                    Console.WriteLine(entityInConflict.CustomerID);
                    foreach (MemberChangeConflict mcc in occ.MemberConflicts)
                    {
                        object     currVal     = mcc.CurrentValue;
                        object     origVal     = mcc.OriginalValue;
                        object     databaseVal = mcc.DatabaseValue;
                        MemberInfo mi          = mcc.Member;
                        Console.WriteLine("Member: {0}", mi.Name);
                        Console.WriteLine("current value: {0}", currVal);
                        Console.WriteLine("original value: {0}", origVal);
                        Console.WriteLine("database value: {0}", databaseVal);
                    }
                }
            }
            catch (Exception ee)
            {
                // Catch other exceptions.
                Console.WriteLine(ee.Message);
            }
            finally
            {
                Console.WriteLine("TryCatch block has finished.");
            }
            // </Snippet2>
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            // 使用连接字符串连接数据库
            Northwnd db = new Northwnd(CONNECT_STRING);

            Customer newCust = new Customer();

            newCust.CompanyName = "AdventureWorks Cafe";
            newCust.CustomerID  = "ADVCA";

            db.Customers.InsertOnSubmit(newCust);

            Console.WriteLine("\nCustomers matching CA before insert");
            foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("CA")))
            {
                Console.WriteLine("{0}, {1}, {2}",
                                  c.CustomerID, c.CompanyName, c.Orders.Count);
            }

            var existingCust =
                (from c in db.Customers
                 where c.CustomerID == "ALFKI"
                 select c).First();

            existingCust.ContactName = "New Contact";

            Order       order0  = existingCust.Orders[0];
            OrderDetail detail0 = order0.OrderDetails[0];

            // Display the order to be deleted.
            Console.WriteLine("The Order Detail to be deleted is: OrderID = {0}, ProductID = {1}",
                              detail0.OrderID, detail0.ProductID);
            // Mark the Order Detail row for deletion from the database.
            db.OrderDetails.DeleteOnSubmit(detail0);

            db.SubmitChanges();

            Console.WriteLine("\nCustomers matching CA after update");
            foreach (var c in db.Customers.Where(cust =>
                                                 cust.CustomerID.Contains("CA")))
            {
                Console.WriteLine("{0}, {1}, {2}",
                                  c.CustomerID, c.CompanyName, c.Orders.Count);
            }

            // Keep the console window open after activity stops.
            Console.ReadLine();
        }
Ejemplo n.º 17
0
        void method4()
        {
            // <Snippet4>
            Northwnd nw = new Northwnd(@"northwnd.mdf");
            var      deleteIndivCust =
                from cust in nw.Customers
                where cust.CustomerID == "98128"
                select cust;

            if (deleteIndivCust.Count() > 0)
            {
                nw.Customers.DeleteOnSubmit(deleteIndivCust.First());
                nw.SubmitChanges();
            }
            // </Snippet4>
        }
Ejemplo n.º 18
0
        void method4()
        {
            Northwnd db = new Northwnd(@"c:\linqtest6\northwnd.mdf");

            // <Snippet4>
            // Query for specific customer.
            // First() returns one object rather than a collection.
            var existingCust =
                (from c in db.Customers
                 where c.CustomerID == "ALFKI"
                 select c)
                .First();

            // Change the contact name of the customer.
            existingCust.ContactName = "New Contact";
            // </Snippet4>

            // <Snippet5>
            // Access the first element in the Orders collection.
            Order ord0 = existingCust.Orders[0];

            // Access the first element in the OrderDetails collection.
            OrderDetail detail0 = ord0.OrderDetails[0];

            // Display the order to be deleted.
            Console.WriteLine
                ("The Order Detail to be deleted is: OrderID = {0}, ProductID = {1}",
                detail0.OrderID, detail0.ProductID);

            // Mark the Order Detail row for deletion from the database.
            db.OrderDetails.DeleteOnSubmit(detail0);
            // </Snippet5>

            // <Snippet6>
            db.SubmitChanges();
            // </Snippet6>

            // <Snippet7>
            Console.WriteLine("\nCustomers matching CA after update");
            foreach (var c in db.Customers.Where(cust =>
                                                 cust.CustomerID.Contains("CA")))
            {
                Console.WriteLine("{0}, {1}, {2}",
                                  c.CustomerID, c.CompanyName, c.Orders.Count);
            }
            // </Snippet7>
        }
Ejemplo n.º 19
0
        void method3()
        {
            // <Snippet3>
            Northwnd nw = new Northwnd(@"northwnd.mdf");

            var cityNameQuery =
                from cust in nw.Customers
                where cust.City.Contains("London")
                select cust;

            foreach (var customer in cityNameQuery)
            {
                if (customer.City == "London")
                {
                    customer.City = "London - Metro";
                }
            }
            nw.SubmitChanges();
            // </Snippet3>
        }
Ejemplo n.º 20
0
        void method2()
        {
            // <Snippet2>
            // Northwnd inherits from System.Data.Linq.DataContext.
            Northwnd nw = new Northwnd(@"northwnd.mdf");

            Customer cust = new Customer();

            cust.CompanyName = "SomeCompany";
            cust.City        = "London";
            cust.CustomerID  = "98128";
            cust.PostalCode  = "55555";
            cust.Phone       = "555-555-5555";
            nw.Customers.InsertOnSubmit(cust);

            // At this point, the new Customer object is added in the object model.
            // In LINQ to SQL, the change is not sent to the database until
            // SubmitChanges is called.
            nw.SubmitChanges();
            // </Snippet2>
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            // <Snippet1>
            using (Northwnd db = new Northwnd(@"c:\northwnd.mdf"))
            {
                // Get original Customer from deserialization.
                var    q1          = db.Orders.First();
                string serializedQ = SerializeHelper.Serialize(q1);
                var    q2          = SerializeHelper.Deserialize(serializedQ, q1);

                // Track this object for an update (not insert).
                db.Orders.Attach(q2, false);

                // Replay the changes.
                q2.ShipRegion  = "King";
                q2.ShipAddress = "1 Microsoft Way";

                // DataContext knows how to update the order.
                db.SubmitChanges();
            }
            // </Snippet1>
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            // <Snippet1>
            // Add 'using System.Reflection' for this section.
            Northwnd db = new Northwnd("...");

            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }

            catch (ChangeConflictException e)
            {
                Console.WriteLine("Optimistic concurrency error.");
                Console.WriteLine(e.Message);
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    MetaTable metatable        = db.Mapping.GetTable(occ.Object.GetType());
                    Customer  entityInConflict = (Customer)occ.Object;
                    Console.WriteLine("Table name: {0}", metatable.TableName);
                    Console.Write("Customer ID: ");
                    Console.WriteLine(entityInConflict.CustomerID);
                    foreach (MemberChangeConflict mcc in occ.MemberConflicts)
                    {
                        object     currVal     = mcc.CurrentValue;
                        object     origVal     = mcc.OriginalValue;
                        object     databaseVal = mcc.DatabaseValue;
                        MemberInfo mi          = mcc.Member;
                        Console.WriteLine("Member: {0}", mi.Name);
                        Console.WriteLine("current value: {0}", currVal);
                        Console.WriteLine("original value: {0}", origVal);
                        Console.WriteLine("database value: {0}", databaseVal);
                        Console.ReadLine();
                    }
                }
            }
            // </Snippet1>
        }
Ejemplo n.º 23
0
        void method3()
        {
            // <Snippet3>
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    Product prod1 = db.Products.First(p => p.ProductID == 4);
                    Product prod2 = db.Products.First(p => p.ProductID == 5);
                    prod1.UnitsInStock -= 3;
                    prod2.UnitsInStock -= 5;
                    db.SubmitChanges();
                    ts.Complete();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            // </Snippet3>
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            Northwnd db = new Northwnd(@"");

            // <Snippet1>
            db.Connection.Close();
            // </Snippet1>

            // <Snippet2>
            using (TransactionScope ts = new TransactionScope())
            {
                db.SubmitChanges();
                ts.Complete();
            }
            // </Snippet2>

            // <Snippet3>
            IEnumerable <Customer> results = db.ExecuteQuery <Customer>(
                @"select c1.custid as CustomerID, c2.custName as ContactName
        from customer1 as c1, customer2 as c2
        where c1.custid = c2.custid"
                );
            // </Snippet3>
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            // <Snippet1>
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            db.Log = Console.Out;

            // Specify order to be removed from database
            int reqOrder = 10250;

            // Fetch OrderDetails for requested order.
            var ordDetailQuery =
                from odq in db.OrderDetails
                where odq.OrderID == reqOrder
                select odq;

            foreach (var selectedDetail in ordDetailQuery)
            {
                Console.WriteLine(selectedDetail.Product.ProductID);
                db.OrderDetails.DeleteOnSubmit(selectedDetail);
            }

            // Display progress.
            Console.WriteLine("detail section finished.");
            Console.ReadLine();

            // Determine from Detail collection whether parent exists.
            if (ordDetailQuery.Any())
            {
                Console.WriteLine("The parent is presesnt in the Orders collection.");
                // Fetch Order.
                try
                {
                    var ordFetch =
                        (from ofetch in db.Orders
                         where ofetch.OrderID == reqOrder
                         select ofetch).First();
                    db.Orders.DeleteOnSubmit(ordFetch);
                    Console.WriteLine("{0} OrderID is marked for deletion.", ordFetch.OrderID);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("There was no parent in the Orders collection.");
            }


            // Display progress.
            Console.WriteLine("Order section finished.");
            Console.ReadLine();

            try
            {
                db.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }

            // Display progress.
            Console.WriteLine("Submit finished.");
            Console.ReadLine();
            // </Snippet1>
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            //  Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            // <Snippet1>
// DataContext takes a connection string.
            DataContext db = new DataContext(@"c:\Northwind.mdf");

// Get a typed table to run queries.
            Table <Customer> Customers = db.GetTable <Customer>();

// Query for customers from London.
            var query =
                from cust in Customers
                where cust.City == "London"
                select cust;

            foreach (var cust in query)
            {
                Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);
            }
            // </Snippet1>

            // <Snippet3>
            db.ExecuteCommand("UPDATE Products SET UnitPrice = UnitPrice + 1.00");
            // </Snippet3>

            // <Snippet4>
            string        connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\northwind.mdf;
                Integrated Security=True; Connect Timeout=30; User Instance=True";
            SqlConnection nwindConn  = new SqlConnection(connString);

            nwindConn.Open();

            Northwnd interop_db = new Northwnd(nwindConn);

            SqlTransaction nwindTxn = nwindConn.BeginTransaction();

            try
            {
                SqlCommand cmd = new SqlCommand(
                    "UPDATE Products SET QuantityPerUnit = 'single item' WHERE ProductID = 3");
                cmd.Connection  = nwindConn;
                cmd.Transaction = nwindTxn;
                cmd.ExecuteNonQuery();

                interop_db.Transaction = nwindTxn;

                Product prod1 = interop_db.Products
                                .First(p => p.ProductID == 4);
                Product prod2 = interop_db.Products
                                .First(p => p.ProductID == 5);
                prod1.UnitsInStock -= 3;
                prod2.UnitsInStock -= 5;

                interop_db.SubmitChanges();

                nwindTxn.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Error submitting changes... all changes rolled back.");
            }

            nwindConn.Close();
            // </Snippet4>

            Console.ReadLine();
        } //end of Main