Пример #1
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var sup1 = new Supplier {
                    SupplierId = 1, Name = "CallCom"
                };
                var sup2 = new Supplier {
                    SupplierId = 2, Name = "Toys, Ltd."
                };
                context.Suppliers.AddObject(sup1);
                context.Suppliers.AddObject(sup2);
                context.SaveChanges();

                // insert some products directly
                context.ExecuteStoreCommand("insert into chapter15.product(productid,name,description,stockcount,discontinued) values (1,'Flowers','Dozen red roses',4,1)");
                context.ExecuteStoreCommand("insert into chapter15.product(productid,name,description,stockcount,discontinued,supplierid) values (2,'Red Fire Truck',null,null,0,1)");
            }

            using (var context = new EFRecipesEntities())
            {
                foreach (var p in context.Products)
                {
                    Console.WriteLine("\nName: {0}", p.Name);
                    Console.WriteLine("Stock Count: {0}", p.StockCount.ToString());
                    Console.WriteLine("Discountinued: {0}", p.Discontinued ? "Yes" : "No");
                    Console.WriteLine("Supplier: {0}", p.SupplierName);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #2
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                context.Students.AddObject(new Student {
                    FirstName = "Robert", LastName = "Smith", Degree = "Masters"
                });
                context.Students.AddObject(new Student {
                    FirstName = "Julia", LastName = "Kerns", Degree = "Masters"
                });
                context.Students.AddObject(new Student {
                    FirstName = "Nancy", LastName = "Stiles", Degree = "Doctorate"
                });
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                string sql  = "select * from Chapter3.Student where Degree = @Major";
                var    args = new DbParameter[] {
                    new SqlParameter {
                        ParameterName = "Major", Value = "Masters"
                    }
                };
                var students = context.ExecuteStoreQuery <Student>(sql, args);
                Console.WriteLine("Students...");
                foreach (var student in students)
                {
                    Console.WriteLine("{0} {1} is working on a {2} degree", student.FirstName, student.LastName, student.Degree);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #3
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var user1 = new User {
                    FullName = "Robert Meyers", UserName = "******"
                };
                var user2 = new User {
                    FullName = "Karen Kelley", UserName = "******"
                };
                context.Users.AddObject(user1);
                context.Users.AddObject(user2);
                context.SaveChanges();
                Console.WriteLine("Users saved to database");
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine();
                Console.WriteLine("Reading users from database");
                foreach (var user in context.Users)
                {
                    Console.WriteLine("{0} is {1}, UserName is {2}", user.FullName, user.IsActive ? "Active" : "Inactive", user.UserName);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #4
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter14.agent");
     }
 }
Пример #5
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                context.Paintings.AddObject(new Painting {
                    AccessionNumber = "PN001", Name = "Sunflowers", Artist = "Rosemary Golden", LastSalePrice = 1250M
                });
                context.Paintings.AddObject(new Painting {
                    AccessionNumber = "PN002", Name = "Red River", Artist = "Alex Jones", LastSalePrice = 1800M
                });
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // let's assume we already know the key for the painting
                var      p        = context.GetObjectByKey(new System.Data.EntityKey("EFRecipesEntities.Paintings", "AccessionNumber", "PN001"));
                Painting painting = (Painting)p;
                Console.WriteLine("The painting with accession number {0}", painting.AccessionNumber);
                Console.WriteLine("\tName: {0}", painting.Name);
                Console.WriteLine("\tArtist: {0}", painting.Artist);
                Console.WriteLine("\tSale Price: {0}", painting.LastSalePrice.ToString("C"));
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #6
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter10.rental");
         context.ExecuteStoreCommand("delete from chapter10.vehicle");
     }
 }
Пример #7
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter15.Product");
         context.ExecuteStoreCommand("delete from chapter15.supplier");
     }
 }
Пример #8
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter6.workertask");
         context.ExecuteStoreCommand("delete from chapter6.worker");
         context.ExecuteStoreCommand("delete from chapter6.task");
     }
 }
Пример #9
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter11.invoice");
         context.ExecuteStoreCommand("delete from chapter11.[order]"); // because we re-used tables in this chapter!
         context.ExecuteStoreCommand("delete from chapter11.customer");
     }
 }
Пример #10
0
 private static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.Database.ExecuteSqlCommand("delete from chapter5.customeremail");
         context.Database.ExecuteSqlCommand("delete from chapter5.customer");
         context.Database.ExecuteSqlCommand("delete from chapter5.customertype");
     }
 }
Пример #11
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter5.sectionstudent");
         context.ExecuteStoreCommand("delete from chapter5.section");
         context.ExecuteStoreCommand("delete from chapter5.student");
         context.ExecuteStoreCommand("delete from chapter5.course");
         context.ExecuteStoreCommand("delete from chapter5.instructor");
     }
 }
Пример #12
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var worker = new Worker {
                    Name = "Jim"
                };
                var task = new Task {
                    Title = "Fold Envelopes"
                };
                var workertask = new WorkerTask {
                    Task = task, Worker = worker
                };
                context.WorkerTasks.AddObject(workertask);
                task = new Task {
                    Title = "Mail Letters"
                };
                workertask = new WorkerTask {
                    Task = task, Worker = worker
                };
                context.WorkerTasks.AddObject(workertask);
                worker = new Worker {
                    Name = "Sara"
                };
                task = new Task {
                    Title = "Buy Envelopes"
                };
                workertask = new WorkerTask {
                    Task = task, Worker = worker
                };
                context.WorkerTasks.AddObject(workertask);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                context.ContextOptions.LazyLoadingEnabled = true;
                Console.WriteLine("Workers and Their Tasks");
                Console.WriteLine("=======================");
                foreach (var worker in context.Workers)
                {
                    Console.WriteLine("\n{0}'s tasks:", worker.Name);
                    foreach (var wt in worker.WorkerTasks)
                    {
                        Console.WriteLine("\t{0}", wt.Task.Title);
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #13
0
 public void UpdateOrderByRetrieving(Order order)
 {
     using (var context = new EFRecipesEntities())
     {
         var dbOrder = context.Orders.Single(o => o.OrderId == order.OrderId);
         if (dbOrder != null &&
             StructuralComparisons.StructuralEqualityComparer.Equals(order.TimeStamp, dbOrder.TimeStamp))
         {
             dbOrder.Quantity = order.Quantity;
             context.SaveChanges();
         }
     }
 }
Пример #14
0
 public void UpdateOrderWithoutRetrieving(Order order)
 {
     using (var context = new EFRecipesEntities())
     {
         context.Orders.Attach(order);
         if (order.Status == "Received")
         {
             var entry = context.ObjectStateManager.GetObjectStateEntry(order);
             entry.SetModifiedProperty("Quantity");
             context.SaveChanges();
         }
     }
 }
Пример #15
0
        public Order InsertOrder()
        {
            using (var context = new EFRecipesEntities())
            {
                // remove previous test data
                context.ExecuteStoreCommand("delete from chapter9.[order]");

                var order = new Order {
                    Product = "Camping Tent", Quantity = 3, Status = "Received"
                };
                context.Orders.AddObject(order);
                context.SaveChanges();
                return(order);
            }
        }
Пример #16
0
 public void UpdateOrderByRetrieving(Order order)
 {
     using (var context = new EFRecipesEntities())
     {
         // fetch current entity from database
         var dbOrder = context.Orders.Single(o => o.OrderId == order.OrderId);
         if (dbOrder != null &&
             // execute concurrency check
             StructuralComparisons.StructuralEqualityComparer.Equals(order.TimeStamp, dbOrder.TimeStamp))
         {
             dbOrder.Quantity = order.Quantity;
             context.SaveChanges();
         }
     }
 }
Пример #17
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                context.Agents.AddObject(new Agent {
                    Name = "Phillip Marlowe", Phone = "202 555-1212"
                });
                context.Agents.AddObject(new Agent {
                    Name = "Janet Rooney", Phone = "913 876-5309"
                });
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // change the phone numbers
                var agent1 = context.Agents.Where(a => a.Name == "Janet Rooney").Single();
                var agent2 = context.Agents.Where(a => a.Name == "Phillip Marlowe").Single();
                agent1.Phone = "817 353-4458";
                context.SaveChanges();

                // update the other agent's number out-of-band
                context.ExecuteStoreCommand(@"update Chapter14.agent set Phone = '817 294-6059' where name = 'Phillip Marlowe'");

                // now change it using the model
                agent2.Phone = "817 906-2212";
                try
                {
                    context.SaveChanges();
                }
                catch (OptimisticConcurrencyException ex)
                {
                    Console.WriteLine("Exception caught updating phone number: {0}", ex.Message);
                }
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("-- All Agents --");
                foreach (var agent in context.Agents)
                {
                    Console.WriteLine("Agent: {0}, Phone: {1}", agent.Name, agent.Phone);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #18
0
 public void UpdateOrderWithoutRetrieving(Order order)
 {
     using (var context = new EFRecipesEntities())
     {
         try
         {
             context.Orders.Attach(order);
             if (order.Status == "Received")
             {
                 context.Entry(order).Property(x => x.Quantity).IsModified = true;
                 context.SaveChanges();
             }
         }
         catch (OptimisticConcurrencyException ex)
         {
             // Handle OptimisticConcurrencyException
         }
     }
 }
Пример #19
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         using (var context = new EFRecipesEntities())
         {
             context.ExecuteStoreCommand("delete from chapter4.Member");
             context.Members.AddObject(new Member {
                 Name = "Robert Dewey", Email = "*****@*****.**"
             });
             context.Members.AddObject(new Member {
                 Name = "Nancy Steward", Email = "*****@*****.**"
             });
             context.Members.AddObject(new Member {
                 Name = "Robin Rosen", Email = "*****@*****.**"
             });
             context.SaveChanges();
         }
     }
 }
Пример #20
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var car1 = new Vehicle {
                    Manufacturer = "Toyota", Model = "Camry", Year = 2010
                };
                var car2 = new Vehicle {
                    Manufacturer = "Chevrolet", Model = "Corvette", Year = 2010
                };
                var r1 = new Rental {
                    Vehicle = car1, RentalDate = DateTime.Parse("2/2/2010"), Payment = 59.95M
                };
                var r2 = new Rental {
                    Vehicle = car2, RentalDate = DateTime.Parse("2/2/2010"), Payment = 139.95M
                };
                context.AddToRentals(r1);
                context.AddToRentals(r2);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                string reportDate    = "2/2/2010";
                var    totalRentals  = new ObjectParameter("TotalRentals", typeof(int));
                var    totalPayments = new ObjectParameter("TotalPayments", typeof(decimal));
                var    vehicles      = context.GetVehiclesWithRentals(DateTime.Parse(reportDate), totalRentals, totalPayments);
                Console.WriteLine("Rental Activity for {0}", reportDate);
                Console.WriteLine("Vehicles Rented");
                foreach (var vehicle in vehicles)
                {
                    Console.WriteLine("{0} {1} {2}", vehicle.Year.ToString(), vehicle.Manufacturer, vehicle.Model);
                }
                Console.WriteLine("Total Rentals: {0}", ((int)totalRentals.Value).ToString());
                Console.WriteLine("Total Payments: {0}", ((decimal)totalPayments.Value).ToString("C"));
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #21
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                DateTime d1 = DateTime.Parse("8/8/2009");
                DateTime d2 = DateTime.Parse("8/12/2008");
                var      c1 = new Customer {
                    Name = "Jill Robinson", City = "Dallas"
                };
                var c2 = new Customer {
                    Name = "Jerry Jones", City = "Denver"
                };
                var c3 = new Customer {
                    Name = "Janis Brady", City = "Dallas"
                };
                var c4 = new Customer {
                    Name = "Steve Foster", City = "Dallas"
                };
                context.Invoices.AddObject(new Invoice {
                    Amount = 302.99M, Description = "New Tires", Date = d1, Customer = c1
                });
                context.Invoices.AddObject(new Invoice {
                    Amount = 430.39M, Description = "Brakes and Shocks", Date = d1, Customer = c2
                });
                context.Invoices.AddObject(new Invoice {
                    Amount = 102.28M, Description = "Wheel Alignment", Date = d1, Customer = c3
                });
                context.Invoices.AddObject(new Invoice {
                    Amount = 629.82M, Description = "A/C Repair", Date = d2, Customer = c4
                });
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Using eSql query...");
                string sql      = @"Select value i from 
                         EFRecipesModel.GetInvoices(EFRecipesEntities.Invoices) as i
                         where i.Date > DATETIME'2009-05-1 00:00' 
                         and i.Customer.City = @City";
                var    invoices = context.CreateQuery <Invoice>(sql, new ObjectParameter("City", "Dallas")).Include("Customer");
                foreach (var invoice in invoices)
                {
                    Console.WriteLine("Customer: {0}\tInvoice for: {1}, Amount: {2}", invoice.Customer.Name, invoice.Description, invoice.Amount);
                }
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine();
                Console.WriteLine("Using LINQ query...");
                DateTime date     = DateTime.Parse("5/1/2009");
                var      invoices = from invoice in
                                    MyFunctions.GetInvoices(context.Invoices)
                                    where invoice.Date > date
                                    where invoice.Customer.City == "Dallas"
                                    select invoice;
                foreach (var invoice in ((ObjectQuery <Invoice>)invoices).Include("Customer"))
                {
                    Console.WriteLine("Customer: {0}, Invoice for: {1}, Amount: {2}", invoice.Customer.Name, invoice.Description, invoice.Amount);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #22
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var poet = new Poet {
                    FirstName = "John", LastName = "Milton"
                };
                var poem = new Poem {
                    Title = "Paradise Lost"
                };
                var meter = new Meter {
                    MeterName = "Iambic Pentameter"
                };
                poem.Meter = meter;
                poem.Poet  = poet;
                context.Poems.AddObject(poem);
                poem = new Poem {
                    Title = "Paradise Regained"
                };
                poem.Meter = meter;
                poem.Poet  = poet;
                context.Poems.AddObject(poem);

                poet = new Poet {
                    FirstName = "Lewis", LastName = "Carroll"
                };
                poem = new Poem {
                    Title = "The Hunting of the Shark"
                };
                meter = new Meter {
                    MeterName = "Anapestic Tetrameter"
                };
                poem.Meter = meter;
                poem.Poet  = poet;
                context.Poems.AddObject(poem);

                poet = new Poet {
                    FirstName = "Lord", LastName = "Byron"
                };
                poem = new Poem {
                    Title = "Don Juan"
                };
                poem.Meter = meter;
                poem.Poet  = poet;
                context.Poems.AddObject(poem);

                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                context.ContextOptions.LazyLoadingEnabled = true;
                var poets = from p in context.Poets select p;
                foreach (var poet in poets)
                {
                    Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName);
                    foreach (var poem in poet.Poems)
                    {
                        Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName);
                    }
                }
            }

            // using our vwLibrary view
            using (var context = new EFRecipesEntities())
            {
                var items = from i in context.vwLibraries select i;
                foreach (var item in items)
                {
                    Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
                    Console.WriteLine("\t{0} ({1})", item.Title, item.MeterName);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #23
0
        private static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var web = new CustomerType {
                    Description = "Web Customer", CustomerTypeId = 1
                };
                var retail = new CustomerType {
                    Description = "Retail Customer", CustomerTypeId = 2
                };
                var customer = new Customer {
                    Name = "Joan Smith", CustomerType = web
                };
                customer.CustomerEmails.Add(new CustomerEmail {
                    Email = "*****@*****.**"
                });
                customer.CustomerEmails.Add(new CustomerEmail {
                    Email = "*****@*****.**"
                });
                context.Customers.Add(customer);
                customer = new Customer {
                    Name = "Bill Meyers", CustomerType = retail
                };
                customer.CustomerEmails.Add(new CustomerEmail {
                    Email = "*****@*****.**"
                });
                context.Customers.Add(customer);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // Include() method with a string-based query path to the
                // corresponding navigation properties
                var customers = context.Customers
                                .Include("CustomerType")
                                .Include("CustomerEmails");
                Console.WriteLine("Customers");
                Console.WriteLine("=========");
                foreach (var customer in customers)
                {
                    Console.WriteLine("{0} is a {1}, email address(es)", customer.Name,
                                      customer.CustomerType.Description);
                    foreach (var email in customer.CustomerEmails)
                    {
                        Console.WriteLine("\t{0}", email.Email);
                    }
                }
            }

            using (var context = new EFRecipesEntities())
            {
                // Include() method with a strongly-typed query path to the
                // corresponding navigation properties
                var customerTypes = context.CustomerTypes
                                    .Include(x => x.Customers
                                             .Select(y => y.CustomerEmails));

                Console.WriteLine("\nCustomers by Type");
                Console.WriteLine("=================");
                foreach (var customerType in customerTypes)
                {
                    Console.WriteLine("Customer type: {0}", customerType.Description);
                    foreach (var customer in customerType.Customers)
                    {
                        Console.WriteLine("{0}", customer.Name);
                        foreach (var email in customer.CustomerEmails)
                        {
                            Console.WriteLine("\t{0}", email.Email);
                        }
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Пример #24
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var course = new Course {
                    Title = "Biology 101"
                };
                var fred = new Instructor {
                    Name = "Fred Jones"
                };
                var julia = new Instructor {
                    Name = "Julia Canfield"
                };
                var section1 = new Section {
                    Course = course, Instructor = fred
                };
                var section2 = new Section {
                    Course = course, Instructor = julia
                };
                var jim = new Student {
                    Name = "Jim Roberts"
                };
                jim.Sections.Add(section1);
                var jerry = new Student {
                    Name = "Jerry Jones"
                };
                jerry.Sections.Add(section2);
                var susan = new Student {
                    Name = "Susan O'Reilly"
                };
                susan.Sections.Add(section1);
                var cathy = new Student {
                    Name = "Cathy Ryan"
                };
                cathy.Sections.Add(section2);
                context.Courses.AddObject(course);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                var graph = context.Courses.Include("Sections.Instructor").Include("Sections.Students");
                Console.WriteLine("Courses");
                Console.WriteLine("=======");
                foreach (var course in graph)
                {
                    Console.WriteLine("{0}", course.Title);
                    foreach (var section in course.Sections)
                    {
                        Console.WriteLine("\tSection: {0}, Instrutor: {1}", section.SectionId.ToString(), section.Instructor.Name);
                        Console.WriteLine("\tStudents:");
                        foreach (var student in section.Students)
                        {
                            Console.WriteLine("\t\t{0}", student.Name);
                        }
                        Console.WriteLine("\n");
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }