static void RunExample() { using (var context = new EFRecipesEntities()) { var tech1 = new Technician { Name = "Julie Kerns" }; var tech2 = new Technician { Name = "Robert Allison" }; context.ServiceCalls.AddObject(new ServiceCall { ContactName = "Robin Rosen", Issue = "Can't get satellite signal.", Technician = tech1 }); context.ServiceCalls.AddObject(new ServiceCall { ContactName = "Phillip Marlowe", Issue = "Channel not available", Technician = tech2 }); // now get the entities we've added foreach (var tech in context.ObjectStateManager.GetEntities <Technician>()) { Console.WriteLine("Technician: {0}", tech.Name); foreach (var call in tech.ServiceCalls) { Console.WriteLine("\tService Call: Contact {0} about {1}", call.ContactName, call.Issue); } } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void Cleanup() { using (var context = new EFRecipesEntities()) { context.ExecuteStoreCommand("delete from chapter13.reservation"); } }
static void Cleanup() { using (var context = new EFRecipesEntities()) { context.ExecuteStoreCommand("delete from chapter6.category"); } }
static void RunExample() { using (var context = new EFRecipesEntities()) { var donation = context.CreateObject <Donation>(); donation.Amount = 5000M; var donor1 = context.CreateObject <Donor>(); donor1.Name = "Jill Rosenberg"; var donor2 = context.CreateObject <Donor>(); donor2.Name = "Robert Hewitt"; // give Jill the credit for the donation and save donor1.Donations.Add(donation); context.Donors.AddObject(donor1); context.Donors.AddObject(donor2); context.SaveChanges(); // now give Robert the credit donation.Donor = donor2; // report foreach (var donor in context.Donors) { Console.WriteLine("{0} has given {1} donation(s)", donor.Name, donor.Donations.Count().ToString()); } var entry = context.ObjectStateManager.GetObjectStateEntry(donation); Console.WriteLine("Original Donor Id: {0}", entry.OriginalValues["DonorId"]); Console.WriteLine("Current Donor Id: {0}", entry.CurrentValues["DonorId"]); } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void RunExample() { using (var context = new EFRecipesEntities()) { var course1 = new Course { CourseName = "CS 301" }; var course2 = new Course { CourseName = "Math 455" }; var en1 = new Enrollment { Student = "James Folk" }; var en2 = new Enrollment { Student = "Scott Shores" }; var en3 = new Enrollment { Student = "Jill Glass" }; var en4 = new Enrollment { Student = "Robin Rosen" }; var class1 = new Class { Instructor = "Bill Meyers" }; var class2 = new Class { Instructor = "Norma Hall" }; class1.Course = course1; class2.Course = course2; class1.Enrollments.Add(en1); class1.Enrollments.Add(en2); class2.Enrollments.Add(en3); class2.Enrollments.Add(en4); context.Classes.AddObject(class1); context.Classes.AddObject(class2); context.SaveChanges(); context.Classes.DeleteObject(class1); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { foreach (var course in context.Courses) { Console.WriteLine("Course: {0}", course.CourseName); foreach (var c in course.Classes) { Console.WriteLine("\tClass: {0}, Instructor: {1}", c.ClassId.ToString(), c.Instructor); foreach (var en in c.Enrollments) { Console.WriteLine("\t\tStudent: {0}", en.Student); } } } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void Cleanup() { using (var context = new EFRecipesEntities()) { context.ExecuteStoreCommand("delete from chapter3.comment"); context.ExecuteStoreCommand("delete from chapter3.blogpost"); } }
static void Cleanup() { using (var context = new EFRecipesEntities()) { context.ExecuteStoreCommand("delete from chapter15.invoice"); context.ExecuteStoreCommand("delete from chapter15.client"); } }
static void Cleanup() { using (var context = new EFRecipesEntities()) { context.ExecuteStoreCommand("delete from chapter7.servicecall"); context.ExecuteStoreCommand("delete from chapter7.technician"); } }
static void Cleanup() { using (var context = new EFRecipesEntities()) { context.ExecuteStoreCommand("delete from chapter10.message"); context.ExecuteStoreCommand("delete from chapter10.member"); } }
static void Cleanup() { using (var context = new EFRecipesEntities()) { context.ExecuteStoreCommand("delete from chapter5.employee"); context.ExecuteStoreCommand("delete from chapter5.department"); context.ExecuteStoreCommand("delete from chapter5.company"); } }
static void RunExample() { using (var context = new EFRecipesEntities()) { var hotel = new Hotel { Name = "Five Seasons Resort" }; var v1 = new Visitor { Name = "Alex Stevens" }; var v2 = new Visitor { Name = "Joan Hills" }; var r1 = new Reservation { Cost = 79.99M, Hotel = hotel, ReservationDate = DateTime.Parse("2/19/2010"), Visitor = v1 }; var r2 = new Reservation { Cost = 99.99M, Hotel = hotel, ReservationDate = DateTime.Parse("2/17/2010"), Visitor = v2 }; var r3 = new Reservation { Cost = 109.99M, Hotel = hotel, ReservationDate = DateTime.Parse("2/18/2010"), Visitor = v1 }; var r4 = new Reservation { Cost = 89.99M, Hotel = hotel, ReservationDate = DateTime.Parse("2/17/2010"), Visitor = v2 }; context.Hotels.AddObject(hotel); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { Console.WriteLine("Using eSql..."); var esql = @"Select value v from EFRecipesModel.VisitorSummary(DATETIME'2010-02-16 00:00', 7) as v"; var visitors = context.CreateQuery <DbDataRecord>(esql); foreach (var visitor in visitors) { Console.WriteLine("{0}, Total Reservations: {1}, Revenue: {2:C}", visitor["Name"], visitor["TotalReservations"], visitor["BusinessEarned"]); } } using (var context = new EFRecipesEntities()) { Console.WriteLine(); Console.WriteLine("Using LINQ..."); var visitors = from v in context.VisitorSummary(DateTime.Parse("2/16/2010"), 7) select v; foreach (var visitor in visitors) { Console.WriteLine("{0}, Total Reservations: {1}, Revenue: {2:C}", visitor["Name"], visitor["TotalReservations"], visitor["BusinessEarned"]); } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
private static void Cleanup() { using (var context = new EFRecipesEntities()) { context.Database.ExecuteSqlCommand("delete from chapter5.sectionstudent"); context.Database.ExecuteSqlCommand("delete from chapter5.section"); context.Database.ExecuteSqlCommand("delete from chapter5.student"); context.Database.ExecuteSqlCommand("delete from chapter5.course"); context.Database.ExecuteSqlCommand("delete from chapter5.instructor"); } }
static void RunExample() { using (var context = new EFRecipesEntities()) { context.Reservations.AddObject(new Reservation { Name = "James Jordan", ResDate = DateTime.Parse("4/18/10") }); context.Reservations.AddObject(new Reservation { Name = "Katie Marlowe", ResDate = DateTime.Parse("3/22/10") }); context.Reservations.AddObject(new Reservation { Name = "Roger Smith", ResDate = DateTime.Parse("4/18/10") }); context.Reservations.AddObject(new Reservation { Name = "James Jordan", ResDate = DateTime.Parse("5/12/10") }); context.Reservations.AddObject(new Reservation { Name = "James Jordan", ResDate = DateTime.Parse("6/22/10") }); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { DateTime?searchDate = null; string searchName = "James Jordan"; Console.WriteLine("More complex SQL..."); var query2 = from reservation in context.Reservations let dateMatches = searchDate == null || reservation.ResDate == searchDate let nameMatches = searchName == string.Empty || reservation.Name.Contains(searchName) where dateMatches && nameMatches select reservation; foreach (var reservation in query2) { Console.WriteLine("Found reservation for {0} on {1}", reservation.Name, reservation.ResDate.ToShortDateString()); } Console.WriteLine("Cleaner SQL..."); var query1 = from reservation in context.Reservations where (searchDate == null || reservation.ResDate == searchDate) && (searchName == string.Empty || reservation.Name.Contains(searchName)) select reservation; foreach (var reservation in query1) { Console.WriteLine("Found reservation for {0} on {1}", reservation.Name, reservation.ResDate.ToShortDateString()); } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void RunExample() { using (var context = new EFRecipesEntities()) { var company = new Company { Name = "Acme Products" }; var acc = new Department { Name = "Accounting", Company = company }; var ship = new Department { Name = "Shipping", Company = company }; var emp1 = new Employee { Name = "Jill Carpenter", Department = acc }; var emp2 = new Employee { Name = "Steven Hill", Department = ship }; context.Employees.AddObject(emp1); context.Employees.AddObject(emp2); context.SaveChanges(); } // first approach using (var context = new EFRecipesEntities()) { // assume we already have an employee var jill = context.Employees.Where(o => o.Name == "Jill Carpenter").First(); // now get Jill's department and company var results = context.Employees.Include("Department.Company").Where(o => o.EmployeeId == jill.EmployeeId).First <Employee>(); Console.WriteLine("{0} works in {1} for {2}", jill.Name, jill.Department.Name, jill.Department.Company.Name); } // more efficient, does not retrieve employee again using (var context = new EFRecipesEntities()) { // assume we already have an employee var jill = context.Employees.Where(o => o.Name == "Jill Carpenter").First(); var moreResults = jill.DepartmentReference.CreateSourceQuery().Include("Company").First(); context.Attach(moreResults); Console.WriteLine("{0} works in {1} for {2}", jill.Name, jill.Department.Name, jill.Department.Company.Name); } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
// Note: This is the non-MEST code version. If you use MEST, change // context.Audits.AddObject() to context.Clients.AddObject() and // context.Invoices.AddObject() because these entities are now in their // own entity sets. static void RunExample() { using (var context = new EFRecipesEntities()) { var c1 = new Client { Name = "Joanne Wise" }; var c2 = new Client { Name = "Robert Marr" }; var c3 = new Client { Name = "Shelly King" }; var i1 = new Invoice { Amount = 99.23M }; var i2 = new Invoice { Amount = 29.95M }; c1.Invoices.Add(i1); c3.Invoices.Add(i2); context.Audits.AddObject(c1); context.Audits.AddObject(c2); context.Audits.AddObject(c3); context.SaveChanges(); Console.WriteLine("Waiting 10 seconds to update..."); System.Threading.Thread.Sleep(10 * 1000); i1.Amount = 98.49M; i2.Amount = 39.99M; context.SaveChanges(); } using (var context = new EFRecipesEntities()) { context.ContextOptions.LazyLoadingEnabled = true; Console.WriteLine("Invoices..."); foreach (var bill in context.Audits.OfType <Invoice>()) { Console.WriteLine("{0} Amount: {1}", bill.Client.Name, bill.Amount.ToString("C")); Console.WriteLine("\tCreated: {0}", bill.CreateDate.ToLongTimeString()); Console.WriteLine("\tLast Modified: {0}\n", bill.ModifiedDate.ToLongTimeString()); } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void RunExample() { using (var context = new EFRecipesEntities()) { var louvre = new PictureCategory { Name = "Louvre" }; var child = new PictureCategory { Name = "Egyptian Antiquites" }; louvre.Subcategories.Add(child); child = new PictureCategory { Name = "Sculptures" }; louvre.Subcategories.Add(child); child = new PictureCategory { Name = "Paintings" }; louvre.Subcategories.Add(child); var paris = new PictureCategory { Name = "Paris" }; paris.Subcategories.Add(louvre); var vacation = new PictureCategory { Name = "Summer Vacation" }; vacation.Subcategories.Add(paris); context.PictureCategories.AddObject(paris); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { context.ContextOptions.LazyLoadingEnabled = true; PictureCategory root = (from c in context.PictureCategories where c.ParentCategory == null select c).FirstOrDefault(); Print(root, 0); } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void RunExample() { DateTime today = DateTime.Parse("4/18/2010"); using (var context = new EFRecipesEntities()) { var mem1 = new Member { Name = "Jill Robertson" }; var mem2 = new Member { Name = "Steven Rhodes" }; mem1.Messages.Add(new Message { DateSent = today, MessageBody = "Hello Jim", Subject = "Hello" }); mem1.Messages.Add(new Message { DateSent = today, MessageBody = "Wonderful weather!", Subject = "Weather" }); mem1.Messages.Add(new Message { DateSent = today, MessageBody = "Meet me for lunch", Subject = "Lunch plans" }); mem2.Messages.Add(new Message { DateSent = today, MessageBody = "Going to class today?", Subject = "What's up?" }); context.Members.AddObject(mem1); context.Members.AddObject(mem2); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { Console.WriteLine("Members by message count for {0}", today.ToShortDateString()); var members = context.MembersWithTheMostMessages(today); foreach (var member in members) { Console.WriteLine("Member: {0}", member.Name); } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void RunExample() { using (var context = new EFRecipesEntities()) { context.Accounts.AddObject(new Account { AccountNumber = "8675309", Balance = 100M, Name = "Robin Rosen" }); context.Accounts.AddObject(new Account { AccountNumber = "8535937", Balance = 25M, Name = "Steven Bishop" }); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { // get the account var account = context.Accounts.First(a => a.AccountNumber == "8675309"); Console.WriteLine("Account for {0}", account.Name); Console.WriteLine("\tPrevious Balance: {0}", account.Balance.ToString("C")); // some other process updates the balance Console.WriteLine("[Rogue process updates balance!]"); context.ExecuteStoreCommand("update chapter14.account set balance = 1000 where accountnumber = '8675309'"); // update the account balance account.Balance = 10M; try { Console.WriteLine("\tNew Balance: {0}", account.Balance.ToString("C")); 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 book = new Category { Name = "Books" }; var fiction = new Category { Name = "Fiction", ParentCategory = book }; var nonfiction = new Category { Name = "Non-Fiction", ParentCategory = book }; var novel = new Category { Name = "Novel", ParentCategory = fiction }; var history = new Category { Name = "History", ParentCategory = nonfiction }; context.Categories.AddObject(book); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { var root = context.Categories.Where(o => o.Name == "Books").First(); Console.WriteLine("Parent category is {0}, subcategories are:", root.Name); foreach (var sub in context.GetSubCategories(root.CategoryId)) { Console.WriteLine("\t{0}", sub.Name); } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
static void RunExample() { using (var context = new EFRecipesEntities()) { var post1 = new BlogPost { Title = "The Joy of LINQ", Description = "101 things you always wanted to know about LINQ" }; var post2 = new BlogPost { Title = "LINQ as Dinner Conversation", Description = "What wine goes with a Lambda expression?" }; var post3 = new BlogPost { Title = "LINQ and our Children", Description = "Why we need to teach LINQ in High School" }; var comment1 = new Comment { Comments = "Great post, I wish more people would talk about LINQ" }; var comment2 = new Comment { Comments = "You're right, we should teach LINQ in high school!" }; post1.Comments.Add(comment1); post3.Comments.Add(comment2); context.BlogPosts.AddObject(post1); context.BlogPosts.AddObject(post2); context.BlogPosts.AddObject(post3); context.SaveChanges(); } using (var context = new EFRecipesEntities()) { Console.WriteLine("Blog Posts with comments...(LINQ)"); var posts = from post in context.BlogPosts where post.Comments.Any() select post; foreach (var post in posts) { Console.WriteLine("Blog Post: {0}", post.Title); foreach (var comment in post.Comments) { Console.WriteLine("\t{0}", comment.Comments); } } } Console.WriteLine(); using (var context = new EFRecipesEntities()) { Console.WriteLine("Blog Posts with comments...(ESQL)"); var esql = "select value p from BlogPosts as p where exists(p.Comments)"; var posts = context.CreateQuery <BlogPost>(esql); foreach (var post in posts) { Console.WriteLine("Blog Post: {0}", post.Title); foreach (var comment in post.Comments) { Console.WriteLine("\t{0}", comment.Comments); } } } Console.WriteLine("Press <enter> to continue..."); Console.ReadLine(); }
private 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); course.Sections.Add(section1); course.Sections.Add(section2); context.Students.Add(jim); context.Students.Add(jerry); context.Students.Add(susan); context.Students.Add(cathy); context.Courses.Add(course); context.SaveChanges(); } // String query path argument for the Include method 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, section.Instructor.Name); Console.WriteLine("\tStudents:"); foreach (var student in section.Students) { Console.WriteLine("\t\t{0}", student.Name); } Console.WriteLine("\n"); } } } // Strongly-typed query path argument for the Include method using (var context = new EFRecipesEntities()) { var graph = context.Courses .Include(x => x.Sections.Select(y => y.Instructor)) .Include(x => x.Sections.Select(z => z.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, 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(); }
protected void Page_Load(object sender, EventArgs e) { using (var context = new EFRecipesEntities()) { // cleanup from previous tests context.ExecuteStoreCommand("delete from chapter4.productdetail"); context.ExecuteStoreCommand("delete from chapter4.orderdetail"); context.ExecuteStoreCommand("delete from chapter4.product"); context.ExecuteStoreCommand("delete from chapter4.category"); context.ExecuteStoreCommand("delete from chapter4.supplier"); // add in our test data var s1 = new Supplier { CompanyName = "Backcountry Supply", Country = "USA" }; var s2 = new Supplier { CompanyName = "Alpine Tent", Country = "Italy" }; var s3 = new Supplier { CompanyName = "Ace Footware", Country = "USA" }; var c1 = new Category { CategoryName = "Tents" }; var c2 = new Category { CategoryName = "Shoes/Boots" }; var pd1 = new ProductDetail { UnitPrice = 99.95M }; var pd2 = new ProductDetail { UnitPrice = 129.95M }; var pd3 = new ProductDetail { UnitPrice = 39.95M }; var p1 = new Product { ProductName = "Pup Tent", ProductDescription = "Small and packable tent", Discontinued = true, UnitsInStock = 4 }; var p2 = new Product { ProductName = "Trail Boot", ProductDescription = "Perfect boot for hiking", Discontinued = false, UnitsInStock = 19 }; var p3 = new Product { ProductName = "Family Tent", ProductDescription = "Sleeps 2 adults + 2 children", Discontinued = false, UnitsInStock = 10 }; var od1 = new OrderDetail { UnitPrice = 39.95M, Quantity = 1 }; var od2 = new OrderDetail { UnitPrice = 129.95M, Quantity = 2 }; var od3 = new OrderDetail { UnitPrice = 99.95M, Quantity = 1 }; p1.Supplier = s2; p1.Category = c1; p1.ProductDetail = pd3; p1.OrderDetails.Add(od1); p2.Supplier = s3; p2.Category = c2; p2.OrderDetails.Add(od2); p2.ProductDetail = pd2; p3.Supplier = s1; p3.Category = c1; p3.ProductDetail = pd1; p3.OrderDetails.Add(od3); context.Products.AddObject(p1); context.Products.AddObject(p2); context.Products.AddObject(p3); context.SaveChanges(); } }