コード例 #1
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter6.member");
     }
 }
コード例 #2
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var blogpost = new BlogPosting {
                    Title = "ASP.NET MVC", Author = "Steven Grace", Post = "What's New", Comments = "50"
                };
                var story = new Story {
                    Title = "Time in a Bottle", Author = "Emily Jones", Plot = "Murder on the high seas"
                };
                var ed = new EducationalVideo {
                    Instructor = "Joseph Robins", ResourcePath = "\\videos\asp.wmv", Title = "ASP.NET Examples"
                };
                var movie = new RecreationalVideo {
                    Title = "Archie's Place", Rating = 1, ResourcePath = "\\videos\archie.wmv"
                };
                context.Media.AddObject(blogpost);
                context.Media.AddObject(story);
                context.Media.AddObject(ed);
                context.Media.AddObject(movie);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("All of the media...");
                foreach (var m in context.Media)
                {
                    Console.WriteLine();
                    if (m is BlogPosting)
                    {
                        var post = (BlogPosting)m;
                        Console.WriteLine("Blog Posting");
                        Console.WriteLine("Title: {0}, Author: {1}, Post: {2}", post.Title, post.Author, post.Post);
                    }
                    else if (m is Story)
                    {
                        var story = (Story)m;
                        Console.WriteLine("Story");
                        Console.WriteLine("Title: {0}, Author: {1}, Plot: {2}", story.Title, story.Author, story.Plot);
                    }
                    else if (m is EducationalVideo)
                    {
                        var edvideo = (EducationalVideo)m;
                        Console.WriteLine("Educational Video");
                        Console.WriteLine("Title: {0}, Instructor: {1}", edvideo.Title, edvideo.Instructor);
                    }
                    else if (m is RecreationalVideo)
                    {
                        var video = (RecreationalVideo)m;
                        Console.WriteLine("Recreational Video");
                        Console.WriteLine("Title: {0}, Rating: {1}", video.Title, video.Rating.ToString());
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #3
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter13.track");
         context.ExecuteStoreCommand("delete from chapter13.cd");
     }
 }
コード例 #4
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter5.invoice");
         context.ExecuteStoreCommand("delete from chapter5.client");
     }
 }
コード例 #5
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter3.topselling");
         context.ExecuteStoreCommand("delete from chapter3.product");
     }
 }
コード例 #6
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter12.salesorder");
         context.ExecuteStoreCommand("delete from chapter12.customer");
     }
 }
コード例 #7
0
 private static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.Database.ExecuteSqlCommand("delete from chapter5.appointment");
         context.Database.ExecuteSqlCommand("delete from chapter5.doctor");
         context.Database.ExecuteSqlCommand("delete from chapter5.patient");
     }
 }
コード例 #8
0
 static void Cleanup()
 {
     using (var context = new EFRecipesEntities())
     {
         context.ExecuteStoreCommand("delete from chapter15.article");
         context.ExecuteStoreCommand("delete from chapter15.video");
         context.ExecuteStoreCommand("delete from chapter15.media");
     }
 }
コード例 #9
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var cd1 = context.CreateObject <CD>();
                cd1.Title = "Abbey Road";
                cd1.Tracks.Add(new Track {
                    Title = "Come Together", Artist = "The Beatles"
                });
                var cd2 = context.CreateObject <CD>();
                cd2.Title = "Cowboy Town";
                cd2.Tracks.Add(new Track {
                    Title = "Cowgirls Don't Cry", Artist = "Brooks & Dunn"
                });
                var cd3 = context.CreateObject <CD>();
                cd3.Title = "Long Black Train";
                cd3.Tracks.Add(new Track {
                    Title = "In My Dreams", Artist = "Josh Turner"
                });
                cd3.Tracks.Add(new Track {
                    Title = "Jacksonville", Artist = "Josh Turner"
                });
                context.CDs.AddObject(cd1);
                context.CDs.AddObject(cd2);
                context.CDs.AddObject(cd3);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // trigger proxy generation
                context.CreateProxyTypes(new Type[] { typeof(CD), typeof(Track) });
                Console.WriteLine("{0} proxies generated!", EFRecipesEntities.GetKnownProxyTypes().Count());

                var cds = context.CDs.Include("Tracks");
                foreach (var cd in cds)
                {
                    Console.WriteLine("Album: {0}", cd.Title);
                    foreach (var track in cd.Tracks)
                    {
                        Console.WriteLine("\t{0} by {1}", track.Title, track.Artist);
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #10
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var teen = new Teen {
                    Name = "Steven Keller", Age = 17, Phone = "817 867-5309"
                };
                var adult = new Adult {
                    Name = "Margret Jones", Age = 53, Phone = "913 294-6059"
                };
                var senior = new Senior {
                    Name = "Roland Park", Age = 71, Phone = "816 353-4458"
                };
                context.Members.AddObject(teen);
                context.Members.AddObject(adult);
                context.Members.AddObject(senior);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Club Members");
                Console.WriteLine("============");
                foreach (var member in context.Members)
                {
                    bool   printPhone = true;
                    string str        = string.Empty;
                    if (member is Teen)
                    {
                        str        = " a Teen";
                        printPhone = false;
                    }
                    else if (member is Adult)
                    {
                        str = "an Adult";
                    }
                    else if (member is Senior)
                    {
                        str = "a Senior";
                    }
                    Console.WriteLine("{0} is {1} member, phone: {2}", member.Name, str, printPhone ? member.Phone : "unavailable");
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #11
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var w1 = new WebProduct {
                    Name = "Camping Tent", Description = "Family Camping Tent, Color Green"
                };
                var w2 = new WebProduct {
                    Name = "Chemical Light"
                };
                var w3 = new WebProduct {
                    Name = "Ground Cover", Description = "Blue ground cover"
                };
                context.WebProducts.AddObject(w1);
                context.WebProducts.AddObject(w2);
                context.WebProducts.AddObject(w3);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Query using eSql...");
                var esql  = @"select value EFRecipesModel.Store.ISNULL(p.Description,p.Name)
                             from EFRecipesEntities.WebProducts as p";
                var prods = context.CreateQuery <string>(esql);
                foreach (var prod in prods)
                {
                    Console.WriteLine("Product Description: {0}", prod);
                }
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine();
                Console.WriteLine("Query using LINQ...");
                var prods = from p in context.WebProducts
                            select BuiltinFunctions.ISNULL(p.Description, p.Name);

                foreach (var prod in prods)
                {
                    Console.WriteLine(prod);
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #12
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var name1 = new Name {
                    FirstName = "Robin", LastName = "Rosen"
                };
                var name2 = new Name {
                    FirstName = "Alex", LastName = "St. James"
                };
                var address1 = new Address {
                    AddressLine1 = "510 N. Grant", AddressLine2 = "Apt. 8", City = "Raytown", State = "MO", ZIPCode = "64133"
                };
                var address2 = new Address {
                    AddressLine1 = "222 Baker St.", AddressLine2 = "Apt.22B", City = "Raytown", State = "MO", ZIPCode = "64133"
                };
                context.Agents.AddObject(new Agent {
                    Name = name1, Address = address1
                });
                context.Agents.AddObject(new Agent {
                    Name = name2, Address = address2
                });
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("Agents");
                foreach (var agent in context.Agents)
                {
                    Console.WriteLine("{0} {1}", agent.Name.FirstName, agent.Name.LastName);
                    Console.WriteLine("{0}", agent.Address.AddressLine1);
                    Console.WriteLine("{0}", agent.Address.AddressLine2);
                    Console.WriteLine("{0}, {1} {2}", agent.Address.City, agent.Address.State, agent.Address.ZIPCode);
                    Console.WriteLine();
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #13
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var client1 = new Client {
                    Name = "Karen Standfield", ClientId = 1
                };
                var invoice1 = new Invoice {
                    InvoiceDate = DateTime.Parse("4/1/10"), Amount = 29.95M
                };
                var invoice2 = new Invoice {
                    InvoiceDate = DateTime.Parse("4/2/10"), Amount = 49.95M
                };
                var invoice3 = new Invoice {
                    InvoiceDate = DateTime.Parse("4/3/10"), Amount = 102.95M
                };
                var invoice4 = new Invoice {
                    InvoiceDate = DateTime.Parse("4/4/10"), Amount = 45.99M
                };

                // add the invoice
                // to the client's collection
                client1.Invoices.Add(invoice1);

                // assign the foreign key
                // directly
                invoice2.ClientId = 1;

                // Attach() and existing
                // row using a "fake" entity
                context.ExecuteStoreCommand("insert into chapter5.client values (2, 'Phil Marlowe')");
                var client2 = new Client {
                    ClientId = 2
                };
                context.Clients.Attach(client2);
                invoice3.Client = client2;

                // using the ClientReference
                invoice4.ClientReference.Value = client1;

                // save the changes
                context.Clients.AddObject(client1);
                context.Invoices.AddObject(invoice2);
                context.Invoices.AddObject(invoice3);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                foreach (var client in context.Clients)
                {
                    Console.WriteLine("Client: {0}", client.Name);
                    foreach (var invoice in client.Invoices)
                    {
                        Console.WriteLine("\t{0} for {1}", invoice.InvoiceDate.ToShortDateString(), invoice.Amount.ToString("C"));
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #14
0
        private static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var doc1 = new Doctor {
                    Name = "Joan Meyers"
                };
                var doc2 = new Doctor {
                    Name = "Steven Mills"
                };
                var pat1 = new Patient {
                    Name = "Bill Rivers"
                };
                var pat2 = new Patient {
                    Name = "Susan Stevenson"
                };
                var pat3 = new Patient {
                    Name = "Roland Marcy"
                };

                var app1 = new Appointment
                {
                    Date    = DateTime.Today,
                    Doctor  = doc1,
                    Fee     = 109.92M,
                    Patient = pat1,
                    Reason  = "Checkup"
                };
                var app2 = new Appointment
                {
                    Date    = DateTime.Today,
                    Doctor  = doc2,
                    Fee     = 129.87M,
                    Patient = pat2,
                    Reason  = "Arm Pain"
                };
                var app3 = new Appointment
                {
                    Date    = DateTime.Today,
                    Doctor  = doc1,
                    Fee     = 99.23M,
                    Patient = pat3,
                    Reason  = "Back Pain"
                };

                context.Appointments.Add(app1);
                context.Appointments.Add(app2);
                context.Appointments.Add(app3);

                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                // disable lazy-loading feature as we are explicitly loading
                // child entities
                context.Configuration.LazyLoadingEnabled = false;

                var doctorJoan = context.Doctors.First(o => o.Name == "Joan Meyers");

                if (!context.Entry(doctorJoan).Collection(x => x.Appointments).IsLoaded)
                {
                    context.Entry(doctorJoan).Collection(x => x.Appointments).Load();
                    Console.WriteLine("Dr. {0}'s appointments were explicitly loaded.",
                                      doctorJoan.Name);
                }

                Console.WriteLine("Dr. {0} has {1} appointment(s).",
                                  doctorJoan.Name,
                                  doctorJoan.Appointments.Count());

                foreach (var appointment in context.Appointments)
                {
                    if (!context.Entry(appointment).Reference(x => x.Doctor).IsLoaded)
                    {
                        context.Entry(appointment).Reference(x => x.Doctor).Load();
                        Console.WriteLine("Dr. {0} was explicitly loaded.",
                                          appointment.Doctor.Name);
                    }
                    else
                    {
                        Console.WriteLine("Dr. {0} was already loaded.",
                                          appointment.Doctor.Name);
                    }
                }

                Console.WriteLine("There are {0} appointments for Dr. {1}",
                                  doctorJoan.Appointments.Count(),
                                  doctorJoan.Name);

                doctorJoan.Appointments.Clear();

                Console.WriteLine("Collection clear()'ed");
                Console.WriteLine("There are now {0} appointments for Dr. {1}",
                                  doctorJoan.Appointments.Count(),
                                  doctorJoan.Name);

                context.Entry(doctorJoan).Collection(x => x.Appointments).Load();

                Console.WriteLine("Collection loaded()'ed");

                Console.WriteLine("There are now {0} appointments for Dr. {1}",
                                  doctorJoan.Appointments.Count().ToString(),
                                  doctorJoan.Name);

                // Currently, there isn't an easy way to refresh entities with the DbContext API.
                // Instead, drop-down into the ObjectContext and perform the following actions
                var objectContext = ((IObjectContextAdapter)context).ObjectContext;
                var objectSet     = objectContext.CreateObjectSet <Appointment>();
                objectSet.MergeOption = MergeOption.OverwriteChanges;
                objectSet.Load();

                Console.WriteLine("Collection loaded()'ed with MergeOption.OverwriteChanges");

                Console.WriteLine("There are now {0} appointments for Dr. {1}",
                                  doctorJoan.Appointments.Count(),
                                  doctorJoan.Name);
            }

            // Demonstrating loading part of the collection then Load()'ing the rest
            using (var context = new EFRecipesEntities())
            {
                // disable lazy-loading feature as we are explicitly loading
                // child entities
                context.Configuration.LazyLoadingEnabled = false;

                // Load the first doctor and attach just the first appointment
                var doctorJoan = context.Doctors.First(o => o.Name == "Joan Meyers");

                context.Entry(doctorJoan).Collection(x => x.Appointments).Query().Take(1).Load();

                // note that IsLoaded returns false here since all related data has not been loaded into the context
                var appointmentsLoaded = context.Entry(doctorJoan).Collection(x => x.Appointments).IsLoaded;

                Console.WriteLine("Dr. {0} has {1} appointments loaded.",
                                  doctorJoan.Name,
                                  doctorJoan.Appointments.Count());

                // When we need all of the remaining appointments, simply Load() them
                context.Entry(doctorJoan).Collection(x => x.Appointments).Load();
                Console.WriteLine("Dr. {0} has {1} appointments loaded.",
                                  doctorJoan.Name,
                                  doctorJoan.Appointments.Count());
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #15
0
        static void RunExample()
        {
            using (var context = new EFRecipesEntities())
            {
                var p1 = new Product {
                    Name = "Trailrunner Backpack"
                };
                var p2 = new Product {
                    Name = "Green River Tent", TopSelling = new TopSelling {
                        Rating = 3
                    }
                };
                var p3 = new Product {
                    Name = "Prairie Home Dutch Oven", TopSelling = new TopSelling {
                        Rating = 4
                    }
                };
                var p4 = new Product {
                    Name = "QuickFire Fire Starter", TopSelling = new TopSelling {
                        Rating = 2
                    }
                };
                context.Products.AddObject(p1);
                context.Products.AddObject(p2);
                context.Products.AddObject(p3);
                context.Products.AddObject(p4);
                context.SaveChanges();
            }

            using (var context = new EFRecipesEntities())
            {
                var products = from p in context.Products
                               orderby p.TopSelling.Rating descending
                               select p;
                Console.WriteLine("Top selling products sorted by rating");
                foreach (var product in products)
                {
                    if (product.TopSelling != null)
                    {
                        Console.WriteLine("\t{0} [rating: {1}]", product.Name, product.TopSelling.Rating.ToString());
                    }
                }
            }

            using (var context = new EFRecipesEntities())
            {
                var products = from p in context.Products
                               join t in context.TopSellings on p.ProductId equals t.ProductId into g
                               from tps in g.DefaultIfEmpty()
                               orderby tps.Rating descending
                               select new
                {
                    Name   = p.Name,
                    Rating = tps.Rating == null ? 0 : tps.Rating
                };

                Console.WriteLine("\nTop selling products sorted by rating");
                foreach (var product in products)
                {
                    if (product.Rating != 0)
                    {
                        Console.WriteLine("\t{0} [rating: {1}]", product.Name, product.Rating.ToString());
                    }
                }
            }

            using (var context = new EFRecipesEntities())
            {
                var esql     = @"select value p from products as p
                             order by case when p.TopSelling is null then 0
                                                else p.TopSelling.Rating end desc";
                var products = context.CreateQuery <Product>(esql);
                Console.WriteLine("\nTop selling products sorted by rating");
                foreach (var product in products)
                {
                    if (product.TopSelling != null)
                    {
                        Console.WriteLine("\t{0} [rating: {1}]", product.Name, product.TopSelling.Rating.ToString());
                    }
                }
            }

            Console.WriteLine("Press <enter> to continue...");
            Console.ReadLine();
        }
コード例 #16
0
        static void RunExample()
        {
            // bad order date
            using (var context = new EFRecipesEntities())
            {
                var customer = new Customer {
                    Name = "Phil Marlowe"
                };
                var order = new SalesOrder {
                    OrderDate = DateTime.Parse("3/12/18"), Amount = 19.95M, Status = "Approved", ShippingCharge = 3.95M, Customer = customer
                };
                context.Customers.AddObject(customer);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // order shipped before it was ordered
            using (var context = new EFRecipesEntities())
            {
                var customer = new Customer {
                    Name = "Phil Marlowe"
                };
                var order = new SalesOrder {
                    OrderDate = DateTime.Parse("3/12/10"), Amount = 19.95M, Status = "Approved", ShippingCharge = 3.95M, Customer = customer
                };
                context.Customers.AddObject(customer);
                context.SaveChanges();
                try
                {
                    order.Shipped     = true;
                    order.ShippedDate = DateTime.Parse("3/10/10");
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // order shipped, but not approved
            using (var context = new EFRecipesEntities())
            {
                var customer = new Customer {
                    Name = "Phil Marlowe"
                };
                var order = new SalesOrder {
                    OrderDate = DateTime.Parse("3/12/10"), Amount = 19.95M, Status = "Pending", ShippingCharge = 3.95M, Customer = customer
                };
                context.Customers.AddObject(customer);
                context.SaveChanges();
                try
                {
                    order.Shipped     = true;
                    order.ShippedDate = DateTime.Parse("3/13/10");
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // order over $5,000 and shipping not free
            using (var context = new EFRecipesEntities())
            {
                var customer = new Customer {
                    Name = "Phil Marlowe"
                };
                var order = new SalesOrder {
                    OrderDate = DateTime.Parse("3/12/10"), Amount = 6200M, Status = "Approved", ShippingCharge = 59.95M, Customer = customer
                };
                context.Customers.AddObject(customer);
                context.SaveChanges();
                try
                {
                    order.Shipped     = true;
                    order.ShippedDate = DateTime.Parse("3/13/10");
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // order deleted after it was shipped
            using (var context = new EFRecipesEntities())
            {
                var customer = new Customer {
                    Name = "Phil Marlowe"
                };
                var order = new SalesOrder {
                    OrderDate = DateTime.Parse("3/12/10"), Amount = 19.95M, Status = "Approved", ShippingCharge = 3.95M, Customer = customer
                };
                context.Customers.AddObject(customer);
                context.SaveChanges();
                order.Shipped     = true;
                order.ShippedDate = DateTime.Parse("3/13/10");
                context.SaveChanges();
                try
                {
                    context.DeleteObject(order);
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

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