Exemplo n.º 1
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var product = new Product {
                    SKU = 147, Description = "Expandable Hydration Pack", Price = 19.97M, ImageURL = "/pack147.jpg"
                };
                context.Products.AddObject(product);
                product = new Product {
                    SKU = 178, Description = "Rugged Ranger Duffel Bag", Price = 39.97M, ImageURL = "/pack178.jpg"
                };
                context.Products.AddObject(product);
                product = new Product {
                    SKU = 186, Description = "Range Field Pack", Price = 98.97M, ImageURL = "/noimage.jp"
                };
                context.Products.AddObject(product);
                product = new Product {
                    SKU = 202, Description = "Small Deployment Back Pack", Price = 29.97M, ImageURL = "/pack202.jpg"
                };
                context.Products.AddObject(product);

                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                foreach (var p in context.Products)
                {
                    Console.WriteLine("{0} {1} {2} {3}", p.SKU, p.Description, p.Price.ToString("C"), p.ImageURL);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 2
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter8.item");
     }
 }
Exemplo n.º 3
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter2.productwebinfo");
         context.ExecuteStoreCommand("delete from chapter2.product");
     }
 }
Exemplo n.º 4
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter11.patientvisit");
         context.ExecuteStoreCommand("delete from chapter11.patient");
     }
 }
Exemplo n.º 5
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                context.Employees.AddObject(new Employee {
                    Name = "Robin Rosen", YearsWorked = 3
                });
                context.Employees.AddObject(new Employee {
                    Name = "John Hancock"
                });
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Employees (using LINQ)");
                var employees = from e in context.Employees
                                select new { Name = e.Name, YearsWorked = e.YearsWorked ?? 0 };
                foreach (var employee in employees)
                {
                    Console.WriteLine("{0}, years worked: {1}", employee.Name, employee.YearsWorked);
                }
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Employees (using ESQL)");
                string esql      = @"select 
                                  e.Name,
                                  case when e.YearsWorked is null then 0
                                       else e.YearsWorked
                                  end as YearsWorked
                                from Employees as e";
                var    employees = context.CreateQuery <DbDataRecord>(esql);
                foreach (var employee in employees)
                {
                    Console.WriteLine("{0}, years worked: {1}", employee.GetString(0), employee.GetInt32(1).ToString());
                }
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Employees (using ESQL w/named constructor)");
                string esql      = @"select value Recipe6.Employee(e.EmployeeId, 
                                  e.Name,
                                  case when e.YearsWorked is null then 0
                                       else e.YearsWorked end) 
                                from Employees as e";
                var    employees = context.CreateQuery <Employee>(esql);
                foreach (var employee in employees)
                {
                    Console.WriteLine("{0}, years worked: {1}", employee.Name, employee.YearsWorked.ToString());
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 6
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter12.step");
         context.ExecuteStoreCommand("delete from chapter12.ingredient");
         context.ExecuteStoreCommand("delete from chapter12.recipe");
     }
 }
Exemplo n.º 7
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter14.Instructor");
         context.ExecuteStoreCommand("delete from chapter14.Student");
         context.ExecuteStoreCommand("delete from chapter14.Person");
     }
 }
Exemplo n.º 8
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter10.magazine");
         context.ExecuteStoreCommand("delete from chapter10.dvd");
         context.ExecuteStoreCommand("delete from chapter10.media");
     }
 }
Exemplo n.º 9
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter15.authorbook");
         context.ExecuteStoreCommand("delete from chapter15.book");
         context.ExecuteStoreCommand("delete from chapter15.author");
     }
 }
Exemplo n.º 10
0
        static void DeleteRelatedEntities <T>(T entity, EFRecipesEntities context) where T : EntityObject
        {
            var entities = ((IEntityWithRelationships)entity).RelationshipManager.GetAllRelatedEnds().SelectMany(e => e.CreateSourceQuery().OfType <EntityObject>()).ToList();

            foreach (var child in entities)
            {
                context.DeleteObject(child);
            }
            context.SaveChanges();
        }
Exemplo n.º 11
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter5.reservation");
         context.ExecuteStoreCommand("delete from chapter5.executivesuite");
         context.ExecuteStoreCommand("delete from chapter5.room");
         context.ExecuteStoreCommand("delete from chapter5.hotel");
     }
 }
Exemplo n.º 12
0
 private static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.Database.ExecuteSqlCommand("delete from chapter5.plumber");
         context.Database.ExecuteSqlCommand("delete from chapter5.foreman");
         context.Database.ExecuteSqlCommand("delete from chapter5.jobsite");
         context.Database.ExecuteSqlCommand("delete from chapter5.location");
         context.Database.ExecuteSqlCommand("delete from chapter5.tradesman");
         context.Database.ExecuteSqlCommand("delete from chapter5.phone");
     }
 }
Exemplo n.º 13
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var b1 = new Book {
                    ISBN = "978-1-847193-81-0", Title = "jQuery Reference Guide"
                };
                var b2 = new Book {
                    ISBN = "978-1-29298333", Title = "jQuery Tips and Tricks"
                };
                var b3 = new Book {
                    ISBN = "978-1033988429", Title = "Silverlight 2"
                };
                var a1 = new Author {
                    Name = "Jonathan Chaffer"
                };
                var a2 = new Author {
                    Name = "Chad Campbell"
                };
                var ab1 = new AuthorBook {
                    Author = a1, Book = b1, IsPrimary = true
                };
                var ab2 = new AuthorBook {
                    Author = a1, Book = b2, IsPrimary = false
                };
                var ab3 = new AuthorBook {
                    Author = a2, Book = b3, IsPrimary = false
                };
                context.AuthorBooks.AddObject(ab1);
                context.AuthorBooks.AddObject(ab2);
                context.AuthorBooks.AddObject(ab3);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                context.ContextOptions.LazyLoadingEnabled = true;
                Console.WriteLine("Authors and Their Books...");
                foreach (var author in context.Authors)
                {
                    Console.WriteLine("{0}", author.Name);
                    foreach (var book in author.Books)
                    {
                        Console.WriteLine("\t{0}, ISBN = {1}", book.Title, book.ISBN);
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 14
0
        public void PromoteToMedicine(DateTime acceptedDate, decimal targetPrice, string marketingName)
        {
            var drug = new Medicine {
                DrugId = this.DrugId
            };

            using (var context = new EFRecipesEntities())
            {
                context.AttachTo("Drugs", drug);
                drug.AcceptedDate = acceptedDate;
                drug.TargetPrice  = targetPrice;
                drug.Name         = marketingName;
                context.SaveChanges();
            }
        }
Exemplo n.º 15
0
        private static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var foreman1 = new Foreman {
                    Name = "Carl Ramsey"
                };
                var foreman2 = new Foreman {
                    Name = "Nancy Ortega"
                };
                var phone = new Phone {
                    Number = "817 867-5309"
                };
                var jobsite = new JobSite
                {
                    JobSiteName = "City Arena",
                    Address     = "123 Main",
                    City        = "Anytown",
                    State       = "TX",
                    ZIPCode     = "76082",
                    Phone       = phone
                };
                jobsite.Foremen.Add(foreman1);
                jobsite.Foremen.Add(foreman2);
                var plumber = new Plumber {
                    Name = "Jill Nichols", Email = "*****@*****.**", JobSite = jobsite
                };
                context.Tradesmen.Add(plumber);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                var plumber =
                    context.Tradesmen.OfType <Plumber>().Include("JobSite.Phone").Include("JobSite.Foremen").First();
                Console.WriteLine("Plumber's Name: {0} ({1})", plumber.Name, plumber.Email);
                Console.WriteLine("Job Site: {0}", plumber.JobSite.JobSiteName);
                Console.WriteLine("Job Site Phone: {0}", plumber.JobSite.Phone.Number);
                Console.WriteLine("Job Site Foremen:");
                foreach (var boss in plumber.JobSite.Foremen)
                {
                    Console.WriteLine("\t{0}", boss.Name);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 16
0
        static void RunExample()
        {
            int itemId = 0;

            using (var context = new EFRecipesEntities())
            {
                var item = new Item {
                    Name = "Xcel Camping Tent", UnitPrice = 99.95M
                };
                context.Items.AddObject(item);
                context.SaveChanges();

                // keep the item id for the next step
                itemId = item.ItemId;
                Console.WriteLine("Item: {0}, UnitPrice: {1}", item.Name, item.UnitPrice.ToString("C"));
            }

            using (var context = new EFRecipesEntities())
            {
                // pretend this is the updated
                // item we received with the new price
                var item = new Item {
                    ItemId = itemId, Name = "Xcel Camping Tent", UnitPrice = 129.95M
                };

                // use our method to get the entity set name
                var itemES = context.GetEntitySet(item);

                // create the entity key
                var key = context.CreateEntityKey(itemES.Name, item);

                // retrieve and update the item
                context.GetObjectByKey(key);
                context.ApplyCurrentValues(itemES.Name, item);
                context.SaveChanges();
            }
            using (var context = new EFRecipesEntities())
            {
                var item = context.Items.Single();
                Console.WriteLine("Item: {0}, UnitPrice: {1}", item.Name, item.UnitPrice.ToString("C"));
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 17
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                for (int i = 0; i < 5000; i++)
                {
                    var account = context.CreateObject <Account>();
                    account.Name    = "Test" + i.ToString();
                    account.Balance = 10M;
                    account.Payments.Add(new Payment {
                        PaidTo = "Test" + (i + 1).ToString(), Paid = 5M
                    });
                    context.Accounts.AddObject(account);
                }
                context.SaveChanges();
                watch.Stop();
                Console.WriteLine("Time to insert: {0} seconds", watch.Elapsed.TotalSeconds.ToString());
            }

            using (var context = new EFRecipesEntities())
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                var accounts = context.Accounts.Include("Payments").ToList();
                watch.Stop();
                Console.WriteLine("Time to read: {0} seconds", watch.Elapsed.TotalSeconds.ToString());

                watch.Restart();
                foreach (var account in accounts)
                {
                    account.Balance += 10M;
                    account.Payments.First().Paid += 1M;
                }
                context.SaveChanges();
                watch.Stop();
                Console.WriteLine("Time to update: {0} seconds", watch.Elapsed.TotalSeconds.ToString());
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 18
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var student = new Student {
                    Name = "Joan Williams", EnrollmentDate = DateTime.Parse("1/12/2010")
                };
                var instructor = new Instructor {
                    Name = "Rodger Keller", HireDate = DateTime.Parse("7/14/1992")
                };
                context.People.AddObject(student);
                context.People.AddObject(instructor);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // find the student and update the enrollment date
                var student = context.People.OfType <Student>().First(s => s.Name == "Joan Williams");
                Console.WriteLine("Updating {0}'s enrollment date", student.Name);

                // out-of-band update occurs
                Console.WriteLine("[Apply rogue update]");
                context.ExecuteStoreCommand(@"update chapter14.person set name = 'Joan Smith'
                        where personId = 
                         (select personId from chapter14.person where name = 'Joan Williams')");

                // change the enrollment date
                student.EnrollmentDate = DateTime.Parse("5/2/2010");
                try
                {
                    context.SaveChanges();
                }
                catch (OptimisticConcurrencyException ex)
                {
                    Console.WriteLine("Exception: {0}", ex.Message);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 19
0
 static void ShowRecipes()
 {
     using (var context = new EFRecipesEntities())
     {
         foreach (var recipe in context.Recipes)
         {
             Console.WriteLine("\n*** {0} ***", recipe.RecipeName);
             Console.WriteLine("Ingredients");
             foreach (var ingredient in recipe.Ingredients)
             {
                 Console.WriteLine("\t{0}", ingredient.Name);
             }
             Console.WriteLine("Steps");
             foreach (var step in recipe.Steps)
             {
                 Console.WriteLine("\t{0}", step.Description);
             }
         }
     }
 }
Exemplo n.º 20
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var recipe1 = new Recipe {
                    RecipeName = "Chicken Risotto"
                };
                var recipe2 = new Recipe {
                    RecipeName = "Baked Chicken"
                };
                recipe1.Steps.Add(new Step {
                    Description = "Bring Broth to a boil"
                });
                recipe1.Steps.Add(new Step {
                    Description = "Slowly add Broth to Rice"
                });
                recipe1.Ingredients.Add(new Ingredient {
                    Name = "1 Cup White Rice"
                });
                recipe1.Ingredients.Add(new Ingredient {
                    Name = "6 Cups Chicken Broth"
                });
                recipe2.Steps.Add(new Step {
                    Description = "Bake at 350 for 35 Minutes"
                });
                recipe2.Ingredients.Add(new Ingredient {
                    Name = "1 lb Chicken"
                });
                context.Recipes.AddObject(recipe1);
                context.Recipes.AddObject(recipe2);
                context.SaveChanges();
                Console.WriteLine("All the Related Entities...");
                ShowRecipes();
                DeleteRelatedEntities(recipe2, context);
                Console.WriteLine("\nAfter Related Entities are Deleted...");
                ShowRecipes();
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            using (var context = new EFRecipesEntities())
            {
                // delete the previous test data
                context.ExecuteStoreCommand("delete from chapter4.contact");

                // insert some new test data
                context.Contacts.AddObject(new Customer {
                    Name = "Joan Ryan", Email = "*****@*****.**"
                });
                context.Contacts.AddObject(new Customer {
                    Name = "Robert Kelly", Email = "*****@*****.**"
                });
                context.Contacts.AddObject(new Employee {
                    Name = "Karen Stanford", HireDate = DateTime.Parse("1/21/2010")
                });
                context.Contacts.AddObject(new Employee {
                    Name = "Phil Marlowe", HireDate = DateTime.Parse("2/12/2009")
                });
                context.SaveChanges();
            }
        }
Exemplo n.º 22
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                context.MediaSet.AddObject(new Magazine {
                    Title = "Field and Stream", PublicationDate = DateTime.Parse("6/12/1945")
                });
                context.MediaSet.AddObject(new Magazine {
                    Title = "National Geographic", PublicationDate = DateTime.Parse("7/15/1976")
                });
                context.MediaSet.AddObject(new DVD {
                    Title = "Harmony Road", PlayTime = "2 hours, 30 minutes"
                });
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                var allMedia = context.GetAllMedia();
                Console.WriteLine("All Media");
                Console.WriteLine("=========");
                foreach (var m in allMedia)
                {
                    if (m is Magazine)
                    {
                        Console.WriteLine("{0} Published: {1}", m.Title, ((Magazine)m).PublicationDate.ToShortDateString());
                    }
                    else if (m is DVD)
                    {
                        Console.WriteLine("{0} Play Time: {1}", m.Title, ((DVD)m).PlayTime);
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 23
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var exDrug1 = new Experimental {
                    Name = "Nanoxol", PrincipalResearcher = "Dr. Susan James"
                };
                var exDrug2 = new Experimental {
                    Name = "Percosol", PrincipalResearcher = "Dr. Bill Minor"
                };
                context.Drugs.AddObject(exDrug1);
                context.Drugs.AddObject(exDrug2);
                context.SaveChanges();

                // Nanoxol just got approved!
                exDrug1.PromoteToMedicine(DateTime.Now, 19.99M, "Treatall");
                context.Detach(exDrug1); // better not use this instance any longer
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Experimental Drugs");
                foreach (var d in context.Drugs.OfType <Experimental>())
                {
                    Console.WriteLine("\t{0} ({1})", d.Name, d.PrincipalResearcher);
                }

                Console.WriteLine("Medicines");
                foreach (var d in context.Drugs.OfType <Medicine>())
                {
                    Console.WriteLine("\t{0} Retails for {1}", d.Name, d.TargetPrice.Value.ToString("C"));
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 24
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var hotel = new Hotel {
                    Name = "Grand Seasons Hotel"
                };
                var r101 = new Room {
                    Rate = 79.95M, Hotel = hotel
                };
                var es201 = new ExecutiveSuite {
                    Rate = 179.95M, Hotel = hotel
                };
                var es301 = new ExecutiveSuite {
                    Rate = 299.95M, Hotel = hotel
                };
                var res1 = new Reservation {
                    StartDate = DateTime.Parse("3/12/2010"), EndDate = DateTime.Parse("3/14/2010"), ContactName = "Roberta Jones", Room = es301
                };
                var res2 = new Reservation {
                    StartDate = DateTime.Parse("1/18/2010"), EndDate = DateTime.Parse("1/28/2010"), ContactName = "Bill Meyers", Room = es301
                };
                var res3 = new Reservation {
                    StartDate = DateTime.Parse("2/5/2010"), EndDate = DateTime.Parse("2/6/2010"), ContactName = "Robin Rosen", Room = r101
                };
                context.Hotels.AddObject(hotel);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // assume we have an instance of hotel
                var hotel = context.Hotels.First();

                var rooms = hotel.Rooms.CreateSourceQuery().Include("Reservations").Where(r => r is ExecutiveSuite && r.Reservations.Any()).OrderBy(r => r.Rate);
                Console.WriteLine("Executive Suites for {0} with reservations", hotel.Name);
                hotel.Rooms.Attach(rooms);
                foreach (var room in hotel.Rooms)
                {
                    Console.WriteLine("\nExecutive Suite {0} is {1} per night", room.RoomId.ToString(), room.Rate.ToString("C"));
                    Console.WriteLine("Current reservations are:");
                    foreach (var res in room.Reservations.OrderBy(r => r.StartDate))
                    {
                        Console.WriteLine("\t{0} thru {1} ({2})", res.StartDate.ToShortDateString(), res.EndDate.ToShortDateString(), res.ContactName);
                    }
                }
            }

            // alternative approach using .OfType<>()
            Console.WriteLine("\n--- Alternative approach using .OfType<>() ---");
            using (var context = new EFRecipesEntities())
            {
                // assume we have an instance of hotel
                var hotel = context.Hotels.First();

                var rooms = hotel.Rooms.CreateSourceQuery().Include("Reservations").OfType <ExecutiveSuite>().Where(r => r.Reservations.Any()).OrderBy(r => r.Rate);
                Console.WriteLine("Executive Suites for {0} with reservations", hotel.Name);
                hotel.Rooms.Attach(rooms);
                foreach (var room in hotel.Rooms)
                {
                    Console.WriteLine("\nExecutive Suite {0} is {1} per night", room.RoomId.ToString(), room.Rate.ToString("C"));
                    Console.WriteLine("Current reservations are:");
                    foreach (var res in room.Reservations.OrderBy(r => r.StartDate))
                    {
                        Console.WriteLine("\t{0} thru {1} ({2})", res.StartDate.ToShortDateString(), res.EndDate.ToShortDateString(), res.ContactName);
                    }
                }
            }



            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 25
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                string hospital = "Oakland General";
                var    p1       = new Patient {
                    Name = "Robin Rosen", Age = 41
                };
                var p2 = new Patient {
                    Name = "Alex Jones", Age = 39
                };
                var p3 = new Patient {
                    Name = "Susan Kirby", Age = 54
                };
                var v1 = new PatientVisit {
                    Cost = 98.38M, Hospital = hospital, Patient = p1
                };
                var v2 = new PatientVisit {
                    Cost = 1122.98M, Hospital = hospital, Patient = p1
                };
                var v3 = new PatientVisit {
                    Cost = 2292.72M, Hospital = hospital, Patient = p2
                };
                var v4 = new PatientVisit {
                    Cost = 1145.73M, Hospital = hospital, Patient = p3
                };
                var v5 = new PatientVisit {
                    Cost = 2891.07M, Hospital = hospital, Patient = p3
                };
                context.Patients.AddObject(p1);
                context.Patients.AddObject(p2);
                context.Patients.AddObject(p3);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Query using eSql...");
                var esql     = @"Select value ps from EFRecipesEntities.Patients as p join EFRecipesModel.GetVisitSummary() as ps on p.Name = ps.Name where p.Age > 40";
                var patients = context.CreateQuery <VisitSummary>(esql);
                foreach (var patient in patients)
                {
                    Console.WriteLine("{0}, Visits: {1}, Total Bill: {2}",
                                      patient.Name, patient.TotalVisits.ToString(), patient.TotalCost.ToString("C"));
                }
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine();
                Console.WriteLine("Query using LINQ...");
                var patients = from p in context.Patients
                               join ps in context.GetVisitSummary() on p.Name equals ps.Name
                               where p.Age >= 40
                               select ps;
                foreach (var patient in patients)
                {
                    Console.WriteLine("{0}, Visits: {1}, Total Bill: {2}",
                                      patient.Name, patient.TotalVisits.ToString(), patient.TotalCost.ToString("C"));
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
Exemplo n.º 26
0
        private static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var hotel = new Hotel {
                    Name = "Grand Seasons Hotel"
                };
                var r101 = new Room {
                    Rate = 79.95M, Hotel = hotel
                };
                var es201 = new ExecutiveSuite {
                    Rate = 179.95M, Hotel = hotel
                };
                var es301 = new ExecutiveSuite {
                    Rate = 299.95M, Hotel = hotel
                };

                var res1 = new Reservation
                {
                    StartDate   = DateTime.Parse("3/12/2010"),
                    EndDate     = DateTime.Parse("3/14/2010"),
                    ContactName = "Roberta Jones",
                    Room        = es301
                };
                var res2 = new Reservation
                {
                    StartDate   = DateTime.Parse("1/18/2010"),
                    EndDate     = DateTime.Parse("1/28/2010"),
                    ContactName = "Bill Meyers",
                    Room        = es301
                };
                var res3 = new Reservation
                {
                    StartDate   = DateTime.Parse("2/5/2010"),
                    EndDate     = DateTime.Parse("2/6/2010"),
                    ContactName = "Robin Rosen",
                    Room        = r101
                };

                es301.Reservations.Add(res1);
                es301.Reservations.Add(res2);
                r101.Reservations.Add(res3);

                hotel.Rooms.Add(r101);
                hotel.Rooms.Add(es201);
                hotel.Rooms.Add(es301);

                context.Hotels.Add(hotel);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // Assume we have an instance of hotel
                var hotel = context.Hotels.First();

                // Explicit loading with Load() provides opportunity to filter related data
                // obtained from the Include() method
                context.Entry(hotel)
                .Collection(x => x.Rooms)
                .Query()
                .Include(y => y.Reservations)
                .Where(y => y is ExecutiveSuite && y.Reservations.Any())
                .Load();

                Console.WriteLine("Executive Suites for {0} with reservations", hotel.Name);

                foreach (var room in hotel.Rooms)
                {
                    Console.WriteLine("\nExecutive Suite {0} is {1} per night", room.RoomId,
                                      room.Rate.ToString("C"));
                    Console.WriteLine("Current reservations are:");
                    foreach (var res in room.Reservations.OrderBy(r => r.StartDate))
                    {
                        Console.WriteLine("\t{0} thru {1} ({2})", res.StartDate.ToShortDateString(),
                                          res.EndDate.ToShortDateString(), res.ContactName);
                    }
                }
            }

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