private static void AddSimpleGraph()
        {
            var essex = new Destination
            {
                Name     = "Essex, Vermont",
                Lodgings = new List <Lodging>
                {
                    new Lodging {
                        Name = "Big Essex Hotel"
                    },
                    new Lodging {
                        Name = "Essex Junction B&B"
                    },
                }
            };

            using (var context = new BreakAwayContext())
            {
                context.Destinations.Add(essex);
                Console.WriteLine("Essex Destination: {0}", context.Entry(essex).State);

                foreach (var lodging in essex.Lodgings)
                {
                    Console.WriteLine("{0}: {1}",
                                      lodging.Name,
                                      context.Entry(lodging).State);
                }
                context.SaveChanges();
            }
        }
Esempio n. 2
0
        private static void SaveDestinationAndLodgings(
            Destination destination,
            List <Lodging> deletedLodgings)
        {
            // TODO: Ensure only Destinations & Lodgings are passed in
            using (var context = new BreakAwayContext())
            {
                context.Destinations.Add(destination);

                if (destination.DestinationId > 0)
                {
                    context.Entry(destination).State = EntityState.Modified;
                }

                foreach (var lodging in destination.Lodgings)
                {
                    if (lodging.LodgingId > 0)
                    {
                        context.Entry(lodging).State = EntityState.Modified;
                    }
                }

                foreach (var lodging in deletedLodgings)
                {
                    context.Entry(lodging).State = EntityState.Deleted;
                }

                context.SaveChanges();
            }
        }
        private static void ListenToLocalChanges()
        {
            using (var context = new BreakAwayContext())
            {
                context.Destinations.Local.CollectionChanged += (sender, args) =>
                {
                    if (args.NewItems != null)
                    {
                        foreach (Destination item in args.NewItems)
                        {
                            Console.WriteLine("Added: " + item.Name);
                        }
                    }

                    if (args.OldItems != null)
                    {
                        foreach (Destination item in args.OldItems)
                        {
                            Console.WriteLine("Removed: " + item.Name);
                        }
                    }
                };

                context.Destinations.Load();
            }
        }
        private static void CreatingNewProxies()
        {
            using (var context = new BreakAwayContext())
            {
                var nonProxy = new Destination();
                nonProxy.Name     = "Non-proxy Destination";
                nonProxy.Lodgings = new List <Lodging>();

                var proxy = context.Destinations.Create();
                proxy.Name = "Proxy Destination";

                context.Destinations.Add(proxy);
                context.Destinations.Add(nonProxy);

                var davesDump = (from l in context.Lodgings
                                 where l.Name == "Dave's Dump"
                                 select l).Single();

                context.Entry(davesDump)
                .Reference(l => l.Destination)
                .Load();

                Console.WriteLine("Before changes: {0}", davesDump.Destination.Name);

                nonProxy.Lodgings.Add(davesDump);
                Console.WriteLine("Added to non-proxy destination: {0}", davesDump.Destination.Name);

                proxy.Lodgings.Add(davesDump);
                Console.WriteLine("Added to proxy destination: {0}", davesDump.Destination.Name);
            }
        }
        private static void AddMultipleDestinations()
        {
            using (var context = new BreakAwayContext())
            {
                context.Configuration.AutoDetectChangesEnabled = false;

                context.Destinations.Add(new Destination
                {
                    Name    = "Paris",
                    Country = "France"
                });

                context.Destinations.Add(new Destination
                {
                    Name    = "Grindelwald",
                    Country = "Switzerland"
                });

                context.Destinations.Add(new Destination
                {
                    Name    = "Crete",
                    Country = "Greece"
                });

                context.SaveChanges();
            }
        }
Esempio n. 6
0
        private static void TestSaveDestinationGraph()
        {
            Destination canyon;

            using (var context = new BreakAwayContext())
            {
                canyon = (from d in context.Destinations.Include(d => d.Lodgings)
                          where d.Name == "Grand Canyon"
                          select d).Single();
            }

            canyon.TravelWarnings = "Carry enough water";
            canyon.State          = State.Modified;

            var firstLodging = canyon.Lodgings.First();

            firstLodging.Name  = "New Name Holiday Park";
            firstLodging.State = State.Modified;

            var secondLodging = canyon.Lodgings.Last();

            secondLodging.State = State.Deleted;

            canyon.Lodgings.Add(new Lodging
            {
                Name  = "Big Canyon Lodge",
                State = State.Added
            });

            ApplyChanges(canyon);
        }
        private static void FindGreatBarrierReef()
        {
            using (var context = new BreakAwayContext())
            {
                var query = from d in context.Destinations
                            where d.Name == "Great Barrier Reef"
                            select d;

                var reef1 = query.Single();
                //Throws exception if no one was found or found more than 1

                var reef = query.SingleOrDefault();
                //Throws exception if found more than 1

/*              If two rows are found, Single and SingleOrDefault will throw because there is not a
 *              single result. If you just want the first result, and aren’t concerned if there is more than
 *              one result, you can use First or FirstOrDefault.*/

/*              One important thing to remember is that LINQ queries against a DbSet always send a
 *              query to the database to find the data. So, if the Great Barrier Reef was a newly added
 *              Destination that hadn’t been saved to the database yet, the queries in Example 2-15
 *              and Example 2-16 won’t be able to locate it.*/

                if (reef == null)
                {
                    Console.WriteLine("Can't find the reef!");
                }
                else
                {
                    Console.WriteLine(reef.Description);
                }
            }
        }
Esempio n. 8
0
        private static void DeleteDestinationInMemoryAndDbCascade()
        {
            int destinationId;

            using (var context = new BreakAwayContext())
            {
                var destination = new Destination
                {
                    Name     = "Sample Destination",
                    Lodgings = new List <Lodging>
                    {
                        new Lodging {
                            Name = "Lodging One"
                        },
                        new Lodging {
                            Name = "Lodging Two"
                        }
                    }
                };
                context.Destinations.Add(destination);
                context.SaveChanges();
                destinationId = destination.DestinationId;
            }
            using (var context = new BreakAwayContext())
            {
                var destination = context.Destinations
                                  .Include("Lodgings")
                                  .Single(d => d.DestinationId == destinationId);
                var aLodging = destination.Lodgings.FirstOrDefault();
                context.Destinations.Remove(destination);
                Console.WriteLine("State of one Lodging: {0}",
                                  context.Entry(aLodging).State.ToString());
                context.SaveChanges();
            }
        }
        private static void ReuseDbConnection()
        {
            var cstr = @"Server=.\SQLEXPRESS;
        Database=BreakAwayDbConnectionConstructor;
        Trusted_Connection=true";

            using (var connection = new SqlConnection(cstr))
            {
                using (var context = new BreakAwayContext(connection))
                {
                    context.Destinations.Add(new Destination {
                        Name = "Hawaii"
                    });
                    context.SaveChanges();
                }

                using (var context = new BreakAwayContext(connection))
                {
                    foreach (var destination in context.Destinations)
                    {
                        Console.WriteLine(destination.Name);
                    }
                }
            }
        }
        static void RunTest()
        {
            using (var context = new BreakAwayContext())
            {
                context.Database.Initialize(force: true);

                context.Destinations.Add(new Destination {
                    Name = "Fiji"
                });
                context.SaveChanges();
            }
            using (var context = new BreakAwayContext())
            {
                if (context.Destinations.Count() == 1)
                {
                    Console.WriteLine(
                        "Test Passed: 1 destination saved to database");
                }
                else
                {
                    Console.WriteLine(
                        "Test Failed: {0} destinations saved to database",
                        context.Destinations.Count());
                }
            }
        }
        private static void TestSaveDestinationAndLodgings()
        {
            Destination canyon;

            using (var context = new BreakAwayContext())
            {
                canyon = (from d in context.Destinations.Include(d => d.Lodgings)
                          where d.Name == "Grand Canyon"
                          select d).Single();
            }

            canyon.TravelWarnings = "Carry enough water!";

            canyon.Lodgings.Add(new Lodging
            {
                Name = "Big Canyon Lodge"
            });

            var firstLodging = canyon.Lodgings.ElementAt(0);

            firstLodging.Name = "New Name Holiday Park";

            var secondLodging   = canyon.Lodgings.ElementAt(1);
            var deletedLodgings = new List <Lodging>();

            canyon.Lodgings.Remove(secondLodging);
            deletedLodgings.Add(secondLodging);

            SaveDestinationAndLodgings(canyon, deletedLodgings);
        }
Esempio n. 12
0
        private static void ApplyChanges <TEntity>(TEntity root) where TEntity : class, IObjectWithState
        {
            using (var context = new BreakAwayContext())
            {
                context.Set <TEntity>().Add(root);

                CheckForEntitiesWithoutStateInterface(context);

                foreach (var entry in context.ChangeTracker
                         .Entries <IObjectWithState>())
                {
                    IObjectWithState stateInfo = entry.Entity;
                    if (stateInfo.State == State.Modified)
                    {
                        entry.State = EntityState.Unchanged;
                        foreach (var property in stateInfo.ModifiedProperties)
                        {
                            entry.Property(property).IsModified = true;
                        }
                    }
                    else
                    {
                        entry.State = ConverterState(stateInfo.State);
                    }
                    entry.State = ConverterState(stateInfo.State);
                }

                context.SaveChanges();
            }
        }
        private static void LocalLinqQueries()
        {
            using (var context = new BreakAwayContext())
            {
                context.Destinations.Load();

                var sortedDestinations = from d in context.Destinations.Local
                                         orderby d.Name
                                         select d;

                Console.WriteLine("All Destinations:");
                foreach (var destination in sortedDestinations)
                {
                    Console.WriteLine(destination.Name);
                }

                var aussieDestinations = from d in context.Destinations.Local
                                         where d.Country == "Australia"
                                         select d;

                Console.WriteLine();
                Console.WriteLine("Australian Destinations:");
                foreach (var destination in aussieDestinations)
                {
                    Console.WriteLine(destination.Name);
                }
            }
        }
/*      Entity Framework queries are written using a .NET Framework feature known as Language
 *      Integrated Query, or LINQ for short. As the name suggests, LINQ is tightly
 *      integrated with the .NET programming experience and provides a strongly typed query
 *      language over your model. Strongly typed simply means that the query is defined using
 *      the classes and properties that make up your model. This provides a number of benefits
 *      such as compile-time checks to ensure your queries are valid and the ability to provide
 *      IntelliSense as you write your queries.
 *      For Entity Framework this provider is known as LINQ to Entities and is responsible for taking
 *      your LINQ query and translating it into a SQL query against the database you are
 *      targeting. The information you supplied to Entity Framework about the shape of your
 *      model and how it maps to the database is used to perform this translation. Once the
 *      query returns, Entity Framework is responsible for copying the data into instances of
 *      the classes that make up your model. */

        //----------------------------------------------
        //Chapter 2 - Querying With DBContext
        //----------------------------------------------

        // Add example methods here
        private static void PrintAustralianDestinations()
        {
            /*  A DbContext (and its underlying ObjectContext) are responsible for managing and
             * tracking changes to instances of the classes in its model. These classes are also responsible
             * for managing a connection to the database. It’s important to ensure that any resources
             * used to perform these operations are cleaned up when the DbContext instance
             * is no longer needed. DbContext implements the standard .NET IDisposable interface,
             * which includes a Dispose method that will release any such resources.
             * The examples in this book will make use of the using pattern, which will take care of
             * disposing the context when the using block completes*/
            using (var context = new BreakAwayContext())
            {
                var query = from d in context.Destinations
                            where d.Country == "Australia"
                            select d;

/*              The query is sent to the database when the first result is requested by the application:
 *              that’s during the first iteration of the foreach loop. Entity Framework doesn’t pull back
 *              all the data at once, though. The query remains active and the results are read from the
 *              database as they are needed. By the time the foreach loop is completed, all the results
 *              have been read from the database.
 *              One important thing to note is that Entity Framework will query the database every
 *              time you trigger an iteration over the contents of a DbSet. This has performance implications
 *              if you are continually querying the database for the same data. To avoid this,
 *              you can use a LINQ operator such as ToList to copy the results into a list. You can then
 *              iterate over the contents of this list multiple times without causing multiple trips to the
 *              database.*/
                foreach (var destination in query)
                {
                    Console.WriteLine(destination.Name);
                }
            }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            try
            {
                var destination = new Destination
                {
                    Country     = "Indonesia",
                    Description = "EcoTourism at its best in exquisite Bali",
                    Name        = "Bali"
                };

                var lodging = new Lodging
                {
                    Name = "Rainy Day Motel",
                };

                var cstr = @"Server=DESKTOP-D51E9P0; Database=BreakAway;User ID=sa;Password=l88888888";
                //Data Source=DESKTOP-D51E9P0;Persist Security Info=True;User ID=sa;Password=***********
                //Data Source=DESKTOP-D51E9P0;Initial Catalog=master;Persist Security Info=True;User ID=sa;Password=***********
                using (var connection = new SqlConnection(cstr))
                {
                    using (var context = new BreakAwayContext(connection))
                    {
                        context.Lodgings.Add(lodging);
                        context.SaveChanges();
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                Console.WriteLine(" 保存失败! 错误信息:" + ex.Message);
            }
            Console.WriteLine("OK");
            Console.Read();
        }
Esempio n. 16
0
        static void DeleteDestinationInMemoryAndDbCascade2()
        {
            //NOTE:
            //随同Destination一起删除以前存入的Loading数据。我们删除与Lodging提到的所有相关代码。
            //由于内存中无Lodging,就不会有客户端的级联删除,而数据库却清除了任何孤立的Lodgings数据,
            //这是因为在数据库中定义了级联删除。

            Guid destinationId;

            using (var context = new BreakAwayContext())
            {
                var destination = new AnnotationModel.Destination
                {
                    Name    = "Sample Destination",
                    Address = new AnnotationModel.Address
                    {
                        City = "City"
                    },
                    Lodgings = new List <AnnotationModel.Lodging>
                    {
                        new AnnotationModel.Lodging
                        {
                            Name = "Lodging One"
                        },
                        new AnnotationModel.Lodging
                        {
                            Name = "Lodging Two"
                        }
                    },
                    Info = new AnnotationModel.PersonalInfo
                    {
                        DietryRestrictions = "DietryRestrictions",
                        Width = new AnnotationModel.Measurement
                        {
                            Reading = 2.1M,
                            Units   = "Units"
                        },
                        Height = new AnnotationModel.Measurement
                        {
                            Reading = 3.1M,
                            Units   = "Units2"
                        }
                    }
                };
                context.Destinations.Add(destination);
                context.SaveChanges();
                destinationId = destination.DestinationId;
            }
            using (var context = new BreakAwayContext())
            {
                var destination = context.Destinations.Single(d => d.DestinationId == destinationId);
                context.Destinations.Remove(destination);
                context.SaveChanges();
            }
            using (var context = new BreakAwayContext())
            {
                var lodgings = context.Lodgings.Where(l => l.DestinationId == destinationId).ToList();
                Console.WriteLine("Lodgings: {0}", lodgings.Count);
            }
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            #if false
            Database.SetInitializer(new InitializeBagaDatabaseWithSeedData());

            using (var context = new BreakAwayContext())
            {
                try
                {
                    /*
                     * force: Zwingt EF dazu die Datenbank an dieser Stelle zu initialisieren.
                     * false: Nur initialisieren wenn das Model noch nicht in der Datenbank ist.
                     * true: Immer neu Initialisieren.
                     */
                    context.Database.Initialize(force: false);
                    Console.WriteLine("Initialization successfully");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Initialization failed...");
                    Console.WriteLine(ex.Message);
                }
            }
            #endif

            Console.ReadKey();
        }
Esempio n. 18
0
        /*
         * public void ex01_AddNewDestination()
         * {
         *  execute(ctx =>
         *  {
         *
         *  });
         * }
         */

        #region private methods

        private void execute(Action <BreakAwayContext> action)
        {
            using (var ctx = new BreakAwayContext())
            {
                ctx.Database.Log = sql => Trace.WriteLine(sql);
                action(ctx);
            }
        }
Esempio n. 19
0
 private static void UpdateDestination(Destination destination)
 {
     using (var context = new BreakAwayContext())
     {
         context.Entry(destination).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
Esempio n. 20
0
 // Serversidesimulation
 private static void AddDestination(Destination destination)
 {
     using (var context = new BreakAwayContext())
     {
         context.Destinations.Add(destination);
         context.SaveChanges();
     }
 }
Esempio n. 21
0
 private static void AttachDestination(Destination destination)
 {
     using (var context = new BreakAwayContext())
     {
         context.Entry(destination).State = EntityState.Unchanged;
         context.SaveChanges();
     }
 }
Esempio n. 22
0
 public void InsertsDestination(Destination destination)
 {
     using (var context = new BreakAwayContext())
     {
         context.Destinations.Add(destination);
         context.SaveChanges();
     }
 }
 private static void UpdateLodging(Lodging lodging)
 {
     using (var context = new BreakAwayContext())
     {
         context.Entry(lodging).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
Esempio n. 24
0
 private static void DeleteDestination(Destination destination)
 {
     using (var context = new BreakAwayContext())
     {
         context.Destinations.Attach(destination);
         context.Destinations.Remove(destination);
         context.SaveChanges();
     }
 }
Esempio n. 25
0
 public static void UpdateSocialSecurityNumber(int ssn)
 {
     using (var context = new BreakAwayContext())
     {
         var person = context.People.FirstOrDefault();
         person.SocialSecurityNumber = ssn;
         context.SaveChanges();
     }
 }
 private static void GetLocalDestinationCountWithLoad()
 {
     using (var context = new BreakAwayContext())
     {
         context.Destinations.Load();
         var count = context.Destinations.Local.Count;
         Console.WriteLine("Destinations in memory: {0}", count);
     }
 }
 private static void UpdateTrip()
 {
     using (var context = new BreakAwayContext())
     {
         var trip = context.Trips.FirstOrDefault();
         trip.CostUSD = 750;
         context.SaveChanges();
     }
 }
Esempio n. 28
0
 public static void UpdateTrip(int usd)
 {
     using (var context = new BreakAwayContext())
     {
         var trip = context.Trips.FirstOrDefault();
         trip.CostUSD = usd;
         context.SaveChanges();
     }
 }
Esempio n. 29
0
 static void UpdatePersonDestination()
 {
     using (var context = new BreakAwayContext())
     {
         var destination = context.Destinations.FirstOrDefault();
         destination.Country = "Rowena";
         context.SaveChanges();
     }
 }
Esempio n. 30
0
 public static void UpdatePerson()
 {
     using (var context = new BreakAwayContext())
     {
         var person = context.Persons.FirstOrDefault();
         person.FirstName = "Rowena";
         context.SaveChanges();
     }
 }