/*      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);
                }
            }
        }
Пример #2
0
 private static void SpecifyDatabaseName()
 {
     using (BreakAwayContext context = new BreakAwayContext("BreakAwayStringConstructor"))
     {
         context.Destinations.Add(new Destination { Name = "Tasmania" });
         context.SaveChanges();
     }
 }
Пример #3
0
 private static void UpdateTrip()
 {
     using (var context = new BreakAwayContext())
     {
         var trip = context.Trips.FirstOrDefault();
         trip.CostUSD = 750;
         context.SaveChanges();
     }
 }
Пример #4
0
 public static void PrintAllDestination()
 {
     using (var context = new BreakAwayContext())
     {
         foreach (Destination destination in context.Destinations)
         {
             Console.WriteLine(destination.Name);
         }
     }
 }
 private static void GetAllLodgings()
 {
     var context = new BreakAwayContext();
     var lodgings = context.Lodgings.ToList();
     foreach (var lodging in lodgings)
     {
         Console.WriteLine("Name: {0}    Type: {1}",
             lodging.Name, lodging.GetType().ToString());
     }
     Console.ReadKey();
 }
        //Deleting Existing Entities

      /* To delete an entity using Entity Framework, you use the Remove method on DbSet.
        Remove works for both existing and newly added entities. Calling Remove on an entity
        that has been added but not yet saved to the database will cancel the addition of the
        entity. The entity is removed from the change tracker and is no longer tracked by the
        DbContext. Calling Remove on an existing entity that is being change-tracked will register
        the entity for deletion the next time SaveChanges is called.
       */

        private static void DeleteWineGlassBay()
        {
            using (var context = new BreakAwayContext())
            {
                var bay = (from d in context.Destinations
                           where d.Name == "Wine Glass Bay"
                           select d).Single();

                context.Destinations.Remove(bay);
                context.SaveChanges();
            }
        }
        //Changing Existing Entities
        private static void ChangeGrandCanyon()
        {
            using (var context = new BreakAwayContext())
            {
                var canyon = (from d in context.Destinations
                              where d.Name == "Grand Canyon"
                              select d).Single();

                canyon.Description = "227 mile long canyon.";
                context.SaveChanges();
            }
        }
 private static void InsertActivities()
 {
     using (var context = new BreakAwayContext())
     {
         var trip = context.Trips.FirstOrDefault();
         trip.Activities = new List<Activity>
         {
             new Activity { Name = "Bicycle Touring" },
             new Activity { Name = "Horse Riding" }
         };
         context.SaveChanges();
     }
 }
Пример #9
0
        static void GetLocalDestinationCount()
        {
            using (var context = new BreakAwayContext())
              {
              foreach (var destination in context.Destinations)
              {
                  Console.WriteLine(destination.Name);
              }

              var count = context.Destinations.Local.Count;
              Console.WriteLine("Destination in memory: {0}", count);
              }
        }
Пример #10
0
 private static void InsertDestination()
 {
     Destination destination = new Destination
     {
         Country = "Indonesia",
         Description = "EcoTourism at its best in esquisite Bali",
         Name = "Bali"
     };
     using(BreakAwayContext context = new BreakAwayContext())
     {
         context.Destinations.Add(destination);
         context.SaveChanges();
     }
 }
        //----------------------------------------------
        //Chapter 2 - Adding Changing And Deleting Entities
        //----------------------------------------------


        //Adding New Entities
        //--------------------------

        private static void AddMachuPicchu()
        {
            using (var context = new BreakAwayContext())
            {
                var machuPicchu = new Destination
                {
                    Name = "Machu Picchu",
                    Country = "Peru"
                };

                context.Destinations.Add(machuPicchu);
                context.SaveChanges();
            }
        }
Пример #12
0
 private static void InserPerson()
 {
     var person = new Person
     {
         Firstname = "Rowne",
         LastName = "Miller",
         SocialSecurityNumber = 12345678
     };
     using (var context = new BreakAwayContext())
     {
         context.Persons.Add(person);
         context.SaveChanges();
     }
 }
Пример #13
0
 private static void InsertTrip()
 {
     Trip trip = new Trip
     {
         CostUSD = 800,
         StartDate = new DateTime(2011, 9, 1),
         EndDate = new DateTime(2011, 9, 14)
     };
     using (BreakAwayContext context = new BreakAwayContext())
     {
         context.Trips.Add(trip);
         context.SaveChanges();
     }
 }
Пример #14
0
 static void FindDestination()
 {
     Console.WriteLine("Enter de id of the destination to find: ");
       var id = int.Parse(Console.ReadLine());
       using (var context = new BreakAwayContext())
       {
       var destination = context.Destinations.Find(id);
       if (destination == null)
       {
           Console.WriteLine("Destination not found");
       }
       else
       {
           Console.WriteLine(destination.Name);
       }
       }
 }
Пример #15
0
        private static void ReuseDbConnection()
        {
            string connStr = @"server=.\sqlexpress;database=BreakAwayDbConnectionConstructor;integrated security = true;";
            
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (BreakAwayContext context = new BreakAwayContext(conn))
                {
                    context.Destinations.Add(new Destination { Name = "Hawaii" });
                }

                using (BreakAwayContext context = new BreakAwayContext(conn))
                {
                    foreach(Destination destination in context.Destinations)
                    {
                        Console.WriteLine(destination.Name);
                    }
                }
            }
        }
        private static void SameWithSortingByName()
        {
            using (var context = new BreakAwayContext())
            {
                var query = from d in context.Destinations
                    where d.Country == "Australia"
                    orderby d.Name
                    select d;

                //Method syntax
                var query1 = context.Destinations
                    .Where(d => d.Country == "Australia")
                    .OrderBy(d => d.Name);

                foreach (var destination in query)
                {
                    Console.WriteLine(destination.Name);
                }
            }
        }
        /* Chapter 6 Validation API 

        Validating a Single Object on Demand with GetValidationResult
         * ------------------------------------------------------------

         * In Destionation Class
         * -------------------------------------------
            [MaxLength(10)]
            public string LastName { get; set; }
         * ---------------------------------------------
 
         *  Now let’s see what happens when we set the length to a string with more than ten
            characters. GetValidationResult allows you to explicitly validate a single entity. It returns
            a ValidationResult type that contains three important members. We’ll focus on
            just one of those for now, the IsValid property, which is a Boolean that indicates if the
            instance passed its validation rules. Let’s use that to validate a Person instance.
         * 
         * 
 
       */

        private static void ValidateNewPerson()
        {
            var person = new Person
            {
                FirstName = "Julie",
                LastName = "Lerman",
                Photo = new PersonPhoto { Photo = new Byte[] { 0 } }
            };
            using (var context = new BreakAwayContext())
            {
                if (context.Entry(person).GetValidationResult().IsValid)
                {
                    Console.WriteLine("Person is Valid");
                }
                else
                {
                    Console.WriteLine("Person is Invalid");
                }
            }
        }
Пример #18
0
 public static void PrintAllDestinationSorted()
 {
     using (var context = new BreakAwayContext())
     {
         IOrderedQueryable<Destination> query = context.Destinations.OrderBy(d => d.Name);
         foreach (Destination destination in query)
         {
             Console.WriteLine(destination.Name);
         }
     }
     //            SELECT [Extent1].[LocationID]     AS [LocationID],
     //       [Extent1].[LocationName]   AS [LocationName],
     //       [Extent1].[Country]        AS [Country],
     //       [Extent1].[Description]    AS [Description],
     //       [Extent1].[Photo]          AS [Photo],
     //       [Extent1].[TravelWarnings] AS [TravelWarnings],
     //       [Extent1].[ClimateInfo]    AS [ClimateInfo]
     //FROM   [baga].[Locations] AS [Extent1]
     //ORDER  BY [Extent1].[LocationName] ASC0
 }
Пример #19
0
        static void FindGreatBarrierRef()
        {
            using (var context = new BreakAwayContext())
              {
              var query = from d in context.Destinations
                          where d.Name == "Great Barrier Reef"
                          select d;

              var reef = query.SingleOrDefault();

              if (reef == null)
              {
                  Console.WriteLine("Can't find the reef!");
              }
              else
              {
                  Console.WriteLine(reef.Description);
              }
              }
        }
        private static void GreatBarrierReefTest()
        {
            using (var context = new BreakAwayContext())
            {
                var reef = from destination in context.Destinations
                           where destination.Name == "Great Barrier Reef"
                           select destination;

                if (reef.Count() == 1)
                {
                    Console.WriteLine(
                        "Test Passed: 1 'Great Barrier Reef' destination found");
                }
                else
                {
                    Console.WriteLine(
                        "Test Failed: {0} 'Great Barrier Reef' destinations found",
                        context.Destinations.Count());
                }
            }
        }
        //Multiple Changes at Once
        private static void MakeMultipleChanges()
        {
            using (var context = new BreakAwayContext())
            {
                var niagaraFalls = new Destination
                {
                    Name = "Niagara Falls",
                    Country = "USA"
                };

                context.Destinations.Add(niagaraFalls);

                var wineGlassBay = (from d in context.Destinations
                    where d.Name == "Wine Glass Bay"
                    select d).Single();

                wineGlassBay.Description = "Picturesque bay with beaches.";

                context.SaveChanges();

            }
        }
Пример #22
0
        /// <summary>
        /// Only once execute Query
        /// </summary>
        public static void PrintAllDestinationTwise()
        {
            using (var context = new BreakAwayContext())
            {
                List<Destination> AllDestination = context.Destinations.ToList();
                foreach (Destination destination in AllDestination)
                {
                    Console.WriteLine(destination.Name);
                }
                foreach (Destination destination in AllDestination)
                {
                    Console.WriteLine(destination.Name);
                }
            }

            //                SELECT [Extent1].[LocationID]     AS [LocationID],
            //       [Extent1].[LocationName]   AS [LocationName],
            //       [Extent1].[Country]        AS [Country],
            //       [Extent1].[Description]    AS [Description],
            //       [Extent1].[Photo]          AS [Photo],
            //       [Extent1].[TravelWarnings] AS [TravelWarnings],
            //       [Extent1].[ClimateInfo]    AS [ClimateInfo]
            //FROM   [baga].[Locations] AS [Extent1]
        }
Пример #23
0
        static void GetLocalDestinationCountWithLoad()
        {
            using (var context = new BreakAwayContext())
              {
              context.Destinations.Load();

              var count = context.Destinations.Local.Count;
              Console.WriteLine("Destination in memory: {0}", count);
              }
        }
Пример #24
0
 // Add example methods here
 static void PrintAllDestinationsSorted()
 {
     using (var context = new BreakAwayContext())
       {
       var query =
           from d in context.Destinations
           where d.Country == "Australia"
           orderby d.Name
           select d;
       foreach (var destination in query)
       {
           Console.WriteLine( destination.Name); }
       }
 }
Пример #25
0
        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);
              }

              //Mira en destinations locales como no la encuentra va a bbdd si pongo el 1 lo busca y lo encuentra en local por lo que no va a bbdd
              var dest = context.Destinations.Find(12);

              if (dest == null)
              {
                  Console.WriteLine("Destination not found");
              }
              else
              {
                  Console.WriteLine(dest.Name);
              }
              }
        }
Пример #26
0
        static void LoadAustralianDestinations()
        {
            using (var context = new BreakAwayContext())
              {
              var query = from d in context.Destinations
                          where d.Country == "Australia"
                          select d;
              query.Load();

              var count = context.Destinations.Local.Count;
              Console.WriteLine("Destination in memory: {0}", count);
              }
        }
Пример #27
0
        static void ListToLocalChanges()
        {
            using (var context = new BreakAwayContext())
              {
              //implementación del delegado con lambda expression
              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();
              }
        }
Пример #28
0
 private static void UpdatePerson()
 {
     using(BreakAwayContext context = new BreakAwayContext())
     {
         Person person = context.People.Include("Photo").FirstOrDefault();
         person.FirstName = "Rowena";                
         if (person.Photo == null)
         {
             person.Photo = new PersonPhoto { Photo = new Byte[] { 0 } };
         }
         context.SaveChanges();
     }
 }
Пример #29
0
        /// <summary>
        /// Projection
        /// </summary>
        public static void PrintDestinationNameOnly()
        {
            using (var context = new BreakAwayContext())
            {
                var query = context.Destinations.Where(d => d.Country == "Australia").Select(x => x.Name).ToList();

                foreach (var name in query)
                {
                    Console.WriteLine(name);
                }
            }
            //            SELECT [Extent1].[LocationName] AS [LocationName]
            //FROM   [baga].[Locations] AS [Extent1]
            //WHERE  N'Australia' = [Extent1].[Country]
        }
Пример #30
0
 public static void PrintAustralianDestination()
 {
     using (var context = new BreakAwayContext())
     {
         IQueryable<Destination> query = context.Destinations.Where(d => d.Country == "Australia");
         foreach (Destination destination in query)
         {
             Console.WriteLine(destination.Name);
         }
     }
     //        SELECT [Extent1].[LocationID]     AS [LocationID],
     //       [Extent1].[LocationName]   AS [LocationName],
     //       [Extent1].[Country]        AS [Country],
     //       [Extent1].[Description]    AS [Description],
     //       [Extent1].[Photo]          AS [Photo],
     //       [Extent1].[TravelWarnings] AS [TravelWarnings],
     //       [Extent1].[ClimateInfo]    AS [ClimateInfo]
     //FROM   [baga].[Locations] AS [Extent1]
     //WHERE  N'Australia' = [Extent1].[Country]
 }