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(); }
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(); } }
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(); }
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(); }
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(); }
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(); }
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(); } }
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(); }
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(); }
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(); }
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(); }
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(); }