public static void BulkDeleteEFCAPIusingPseudoObject()
        {
            CUI.Headline(nameof(BulkDeleteEFCAPIusingPseudoObject));
            int total = 0;
            var sw    = new Stopwatch();

            sw.Start();
            using (var ctx = new WWWingsContext())
            {
                for (int i = 20001; i < 21000; i++)
                {
                    var f = new Flight()
                    {
                        FlightNo = i
                    };
                    ctx.FlightSet.Attach(f);
                    ctx.FlightSet.Remove(f);
                }
                total = ctx.SaveChanges();
            }
            sw.Stop();
            Console.WriteLine("Number of DELETE statements: " + total);
            Console.WriteLine("Duration: " + sw.ElapsedMilliseconds);
            Timer_BulkDeleteEFCAPIusingPseudoObject += sw.ElapsedMilliseconds;
        }
示例#2
0
        public static void Demo_Projection_OneFlight()
        {
            using (var ctx = new WWWingsContext())
            {
                CUI.MainHeadline("Projection");

                var q = from x in ctx.FlightSet
                        where x.FlightNo == 101
                        orderby x.FlightNo
                        select new Flight()
                {
                    FlightNo    = x.FlightNo,
                    Date        = x.Date,
                    Departure   = x.Departure,
                    Destination = x.Destination,
                    Seats       = x.Seats,
                    FreeSeats   = x.FreeSeats,
                };

                var f = q.FirstOrDefault();

                Console.WriteLine(f + " State: " + ctx.Entry(f).State + " Timestamp: " + ByteArrayToString(f.Timestamp));
                ctx.Attach(f);
                Console.WriteLine(f + " State: " + ctx.Entry(f).State + " Timestamp: " + ByteArrayToString(f.Timestamp));
                f.FreeSeats++;
                Console.WriteLine(f + " State: " + ctx.Entry(f).State + " Timestamp: " + ByteArrayToString(f.Timestamp));


                var anz = ctx.SaveChanges();
                Console.WriteLine("Number of saved changes: " + anz);
            }
        }
示例#3
0
        /*
         * The main method is to process action from the user
         */
        static void Main(string[] args)
        {
            //a variable of user input
            int result;
            CUI ui = new CUI();

            //the while loop is for people who logout
            while (true)
            {
                //start the program and show main menu
                result = ui.HomePage();

                if (result == 1)
                {
                    // 1 == sign in
                    //if successfully sign in,redirect to Home Page
                    if (ui.SignInPage())
                    {
                        ui.MainMenuPage();
                    }
                }
                else if (result == 2)
                {
                    //2 == register an account (not bank account)
                    // redirect to register consoleUI
                    ui.RegisterPage();
                }
                // situations that code will reach here.
                // 1.After register an account,require user to sign in
                // 2.some bug, even though result not == 1 || 2, require user to make a action again
                // 3.user logout account.
            }//end of while loop
        }
        public static void GroupBy2()
        {
            CUI.MainHeadline(nameof(GroupBy2));

            using (var ctx = new WWWingsContext())
            {
                ctx.Log();
                //Simple Group by(Number of flights per destination)
                // BUG in EFCore 2.1 Preview 1
                var groups2 = (from p in ctx.FlightSet
                               group p by p.Departure into g
                               select new { City = g.Key, Count = g.Count() }).Where(x => x.Count > 5).OrderBy(x => x.Count).ToList();

                // First roundtrip to the database (done intentionally here!)
                var count2 = groups2.Count();
                Console.WriteLine("Number of groups: " + count2);
                if (count2 > 0)
                {
                    // Second roundtrip to the database
                    foreach (var g in groups2.ToList())
                    {
                        Console.WriteLine(g.City + ": " + g.Count);
                    }
                }
            }
        }
示例#5
0
        public static async void ChangeDataAsync()
        {
            CUI.MainHeadline("Start " + nameof(ChangeDataAsync));
            using (var ctx = new WWWingsContext())
            {
                // Define query
                var query = (from f in ctx.FlightSet.Include(p => p.BookingSet).ThenInclude(b => b.Passenger) where f.Departure == "Rome" && f.FreeSeats > 0 select f).Take(1);
                // Abfrage aynchron ausführen
                CUI.PrintWithThreadID("Start database query");
                var flightSet = await query.ToListAsync();

                CUI.PrintWithThreadID("End database query");
                // Print results
                foreach (Flight flight in flightSet)
                {
                    CUI.PrintWithThreadID("Flight: " + flight.FlightNo + " from " + flight.Departure + " to " +
                                          flight.Destination + " has " + flight.FreeSeats + " free seats");

                    foreach (var b in flight.BookingSet.Take(5))
                    {
                        CUI.PrintWithThreadID(" Passenger:  " + b.Passenger.GivenName + " " + b.Passenger.Surname);
                        CUI.PrintWithThreadID("   Start saving");
                        b.Passenger.Status = 'A';
                        var count = await ctx.SaveChangesAsync();

                        CUI.PrintWithThreadID($"   {count} Changes saved!");
                    }
                }
                CUI.Headline("End " + nameof(ChangeDataAsync));
            }
        }
示例#6
0
        private static void Recreate(bool whatif = false)
        {
            CUI.H1("(Re-)Creating Database...");
            try
            {
                using (var ctx = new Context())
                {
                    if ((ctx.Database.GetService <IDatabaseCreator>() as RelationalDatabaseCreator).Exists())
                    {
                        Console.WriteLine("Deleting database...");
                        if (!whatif)
                        {
                            ctx.Database.EnsureDeleted();
                        }
                        Console.WriteLine("OK!");
                    }
                }

                using (var ctx = new Context())
                {
                    Console.WriteLine("Creating database...");
                    if (!whatif)
                    {
                        ctx.Database.EnsureCreated();
                    }
                    Console.WriteLine("OK!");
                }
            }
            catch (Exception ex)
            {
                PrintError("Recreate Error", ex);
                System.Environment.Exit(2);
            }
        }
示例#7
0
        public static void ColumnsAddedAfterCompilation(bool logging = true)
        {
            CUI.MainHeadline(nameof(ColumnsAddedAfterCompilation));
            // List of additional columns can be read from a config file or the database schema
            List <string> additionalColumnSet = new List <string>()
            {
                "BO.Airline;Address;System.String", "BO.Airline;FoundingYear;System.Nullable`1[System.Int32]", "BO.Airline;Bunkrupt;System.Boolean?", "BO.AircraftType;Role;System.String"
            };

            // List of additional columns must be set before creating the first instance of the context!
            WWWingsContext.AdditionalColumnSet = additionalColumnSet;

            using (WWWingsContext ctx = new WWWingsContext())
            {
                if (logging)
                {
                    ctx.Log();
                }
                // read any Airline object
                var a = ctx.AirlineSet.SingleOrDefault(x => x.Code == "WWW");
                if (a == null)
                {
                    throw new ApplicationException("No Airline found!");
                }
                Console.WriteLine(a);
                Console.WriteLine("Extra columns:");
                foreach (var col in additionalColumnSet.Where(x => x.StartsWith("BO.Airline")))
                {
                    string columnname = col.Split(';')[1];
                    Console.WriteLine(col + "=" + ctx.Entry(a).Property(columnname).CurrentValue);
                }
            }
        }
示例#8
0
 /// <summary>
 /// Let main program warit for key and than exit
 /// </summary>
 public static void End()
 {
     Console.WriteLine("");
     CUI.Print("!!!!!!!!!!!!!!!!!!! Main program is waiting for keypress !!!!!!!!!!!!!!!!", ConsoleColor.Blue, ConsoleColor.White);
     Console.ReadLine();
     Environment.Exit(0);
 }
        public static void Demo_AddGraph()
        {
            CUI.Headline("Demo_AddGraph");

            using (var ctx = new WWWingsContext())
            {
                ctx.Log();
                ctx.Database.ExecuteSqlCommand("Delete from Booking where FlightNo = 101");
                ctx.Database.ExecuteSqlCommand("Delete from Flight where FlightNo = 101");

                var pilot = new Pilot();
                pilot.Surname = "testpilot";
                //ctx.PilotSet.Add(pilot);

                var fneu = new Flight();
                fneu.FlightNo    = 101;
                fneu.Departure   = "Essen";
                fneu.Destination = "Darmstadt";
                fneu.Pilot       = pilot;
                fneu.Seats       = 100;
                fneu.Copilot     = pilot;
                fneu.FreeSeats   = 100;

                ctx.ChangeTracker.TrackGraph(fneu, (obj) => obj.NodeState = obj.Entry.State = EntityState.Added);
                //ctx.ChangeTracker.TrackGraph(fneu, TrackGraph_CallbackAdded);
                ctx.FlightSet.Add(fneu);
                EFC_Util.PrintChangeInfo(ctx);

                var anz = ctx.SaveChanges();

                Console.WriteLine("Saved changes: " + anz);
            }
        }
        public static void Demo_ForeachProblem()
        {
            CUI.Headline(nameof(Demo_ForeachProblem));
            WWWingsContext ctx = new WWWingsContext();
            // Define query
            var query = (from f in ctx.FlightSet.Include(p => p.BookingSet).ThenInclude(b => b.Passenger) where f.Departure == "Rome" && f.FreeSeats > 0 select f).Take(1);

            // Query is performed implicitly by foreach
            foreach (var flight in query)
            {
                // Print results
                CUI.Print("Flight: " + flight.FlightNo + " from " + flight.Departure + " to " + flight.Destination + " has " + flight.FreeSeats + " free seats");

                foreach (var p in flight.BookingSet)
                {
                    CUI.Print(" Passenger  " + p.Passenger.GivenName + " " + p.Passenger.Surname);
                }

                // Save change to every flight object within the loop
                CUI.Print("  Start saving");
                flight.FreeSeats--;
                ctx.SaveChangesAsync(); // SaveChanges() will produce ERROR!!!
                CUI.Print("  End saving");
            }
        }
        public static void GenericHomogeneousList()
        {
            CUI.Headline(nameof(GenericHomogeneousList));

            var PersonSet = new List <Person>();

            for (int i = 0; i < 100; i++)
            {
                PersonSet.Add(new Person()
                {
                    GivenName = "John", Surname = "Doe"
                });
            }

            // define Mapping
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Person, PersonDTO>()
                .ForMember(z => z.Name, map => map.MapFrom(q => q.GivenName + " " + q.Surname))
                .ForMember(z => z.YearOfBirth, map => map.MapFrom(q => q.Birthday.Year));
            });

            // Convert list
            var PersonDTOSet = Mapper.Map <List <PersonDTO> >(PersonSet);

            Console.WriteLine(PersonDTOSet.Count());
            foreach (var p in PersonDTOSet.Take(5))
            {
                Console.WriteLine(p.Name + ": " + p.YearOfBirth);
            }
        }
        public static void AddBatch(short Anz = 400)
        {
            Console.WriteLine(nameof(AddBatch));

            using (var ctx = new WWWingsContext())

            {
                CUI.MainHeadline(Anz + " Add Batch");
                var pilot1 = ctx.PilotSet.FirstOrDefault();
                var pilot2 = ctx.PilotSet.Skip(1).FirstOrDefault();
                ctx.Log();
                ctx.Database.ExecuteSqlCommand("Delete from Booking where FlightNo >= 10000");
                ctx.Database.ExecuteSqlCommand("Delete from Flight where FlightNo >= 10000");

                Stopwatch sw2 = new Stopwatch();
                sw2.Start();
                for (int i = 0; i < Anz; i++)
                {
                    var newFlight = new Flight();
                    newFlight.FlightNo  = 20000 + i;
                    newFlight.Pilot     = pilot1;
                    newFlight.Seats     = 100;
                    newFlight.Copilot   = pilot2;
                    newFlight.FreeSeats = 100;
                    ctx.FlightSet.Add(newFlight);
                }
                ctx.SaveChanges();
                sw2.Stop();
                Console.WriteLine(Anz + " Add Batch: " + sw2.ElapsedMilliseconds + "ms");

                ctx.Database.ExecuteSqlCommand("Delete from Booking where FlightNo >= 10000");
                ctx.Database.ExecuteSqlCommand("Delete from Flight where FlightNo >= 10000");
            }
        }
        public static void ChangeFlightManyProperties()
        {
            CUI.MainHeadline(nameof(ChangeFlightManyProperties));
            int flightNo = 101;

            using (WWWingsContext ctx = new WWWingsContext())
            {
                var f = ctx.FlightSet.SingleOrDefault(x => x.FlightNo == flightNo);

                Console.WriteLine($"After loading: Flight #{f.FlightNo}: {f.Departure}->{f.Destination} has {f.FreeSeats} free seats! State of the Flight object: " + ctx.Entry(f).State);
                f.FreeSeats -= 2;
                //f.Departure = "sdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh";
                f.Memo = $"Last change durch Benutzer {System.Environment.UserName} on {DateTime.Now}.";; // Änderung 2

                Console.WriteLine($"After changes: Flight #{f.FlightNo}: {f.Departure}->{f.Destination} has {f.FreeSeats} free seats! State of the flight object: " + ctx.Entry(f).State);

                try
                {
                    var anz = ctx.SaveChanges();
                    if (anz == 0)
                    {
                        Console.WriteLine("Problem: No changes saved!");
                    }
                    else
                    {
                        Console.WriteLine("Number of saved changes: " + anz);
                    }
                    Console.WriteLine($"After saving: Flight #{f.FlightNo}: {f.Departure}->{f.Destination} has {f.FreeSeats} free seats! State of the Flight object: " + ctx.Entry(f).State);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.ToString());
                }
            }
        }
        public static void BulkDelete_Prepare()
        {
            int countNew = 1000;

            CUI.Headline($"Create records {countNew}...");

            using (var ctx = new WWWingsContext())
            {
                int pilotID = ctx.PilotSet.FirstOrDefault().PersonID;
                for (int i = 0; i < countNew; i++)
                {
                    // Create flight in RAM
                    var f = new Flight();
                    f.FlightNo    = 20000 + i;
                    f.Departure   = "Berlin";
                    f.Destination = "Sydney";
                    f.AirlineCode = "WWW";
                    f.PilotId     = pilotID;
                    f.Seats       = 100;
                    f.FreeSeats   = 100;
                    ctx.FlightSet.Add(f);
                    // or: ctx.Add(f);
                }
                var count = ctx.SaveChanges();
                Console.WriteLine("Number of saved changes: " + count);
            }
        }
        public static void DynamicLINQCompositionBasequery()
        {
            CUI.MainHeadline(nameof(DynamicLINQCompositionBasequery));
            using (WWWingsContext ctx = new WWWingsContext())
            {
                string departure   = "Paris";
                string destination = "";

                IQueryable <Flight> flightBasisQuery = (from f in ctx.FlightSet select f);

                IQueryable <Flight> flightQueryEndgueltig = FreeSeatsMustBeGreaterZeroDynamic(flightBasisQuery);

                if (!String.IsNullOrEmpty(departure))
                {
                    flightQueryEndgueltig = from f in flightQueryEndgueltig where f.Departure == departure select f;
                }
                // or: System.Dynamic.Linq
                //flightQueryEndgueltig = flightQueryEndgueltig.Where("it.Departure = \"Paris\"");

                if (!String.IsNullOrEmpty(destination))
                {
                    flightQueryEndgueltig = from f in flightQueryEndgueltig where f.Destination == destination select f;
                }

                // Send to the database now!
                List <Flight> flightSet = flightQueryEndgueltig.ToList();

                foreach (var f in flightSet)
                {
                    Console.WriteLine("Flight: " + f.FlightNo + " from " + f.Departure + " to " +
                                      f.Destination + " has " + f.FreeSeats + " free seats");
                }
            }
        }
        private static void Attempt2()
        {
            using (var ctx = new WWWingsContext())
            {
                CUI.MainHeadline("Attempt 2: First assignment by foreign key property, then navigation property");
                CUI.PrintStep("Load a flight...");
                var flight101 = ctx.FlightSet.Include(f => f.Pilot).SingleOrDefault(x => x.FlightNo == 101);
                Console.WriteLine($"Flight Nr {flight101.FlightNo} from {flight101.Departure} to {flight101.Destination} has {flight101.FreeSeats} free seats!");
                CUI.Print("Pilot object: " + flight101.Pilot.PersonID + " PilotId: " + flight101.PilotId);

                var neuePilotID2 = GetPilotIdEinesFreienPilots();
                CUI.PrintStep($"Assign a new pilot #{neuePilotID2} via foreign key property...");
                flight101.PilotId = neuePilotID2;
                CUI.Print($"PilotId: {flight101.PilotId} Pilot object: {flight101.Pilot?.PersonID}");

                CUI.PrintStep("Load another pilot...");
                var newPilot1 = ctx.PilotSet.Find(GetPilotIdEinesFreienPilots()); // nächster Pilot
                CUI.PrintStep($"Assign a new pilot #{newPilot1.PersonID} via navigation property...");
                flight101.Pilot = newPilot1;
                CUI.Print($"PilotId: {flight101.PilotId} Pilot object: {flight101.Pilot?.PersonID}");

                CUI.PrintStep("SaveChanges()");
                var anz2 = ctx.SaveChanges();
                CUI.PrintSuccess("Number of saved changes: " + anz2);

                CUI.PrintStep("Control output after saving: ");
                CUI.Print($"PilotId: {flight101.PilotId} Pilot object: {flight101.Pilot?.PersonID}");
            }
        }
        /// <summary>
        ///  Attach()/EntityState.Modified --> All Spalten zurückschreiben
        /// </summary>
        public static void Attached_Flight()
        {
            CUI.MainHeadline(nameof(Attached_Flight));
            Flight f;

            CUI.Print("Lade Objekt in Kontextinstanz #1");
            using (WWWingsContext ctx1 = new WWWingsContext())
            {
                ctx1.Log();
                f = ctx1.FlightSet.Find(101);


                CUI.Print("Objekt ändern");
                CUI.Print(f.ToString());
                f.Memo = "last changed at " + DateTime.Now;
                f.FreeSeats--;
                CUI.Print(f.ToString());


                var count = ctx1.SaveChanges();
                Console.WriteLine("Saved changes: " + count.ToString());
                if (count != 1)
                {
                    Debugger.Break();
                }
            }
        }
示例#18
0
        private static void Init_Pilot(WWWingsV1Context ctx)
        {
            Console.WriteLine("Create pilots...");

            for (int PNummer = 1; PNummer <= NO_OF_PILOTS; PNummer++)
            {
                string Vorname = PilotsVornamen[rnd.Next(0, PilotsVornamen.Length - 1)];
                ;
                string Nachname = PilotsNachnamen[rnd.Next(0, PilotsNachnamen.Length - 1)];
                ;
                Pilot    pi = new Pilot();
                Employee e  = new Employee();
                Person   p  = new Person();
                p.Surname   = Nachname;
                p.GivenName = Vorname;
                p.Birthday  = new DateTime(1940, 1, 1).AddDays(Convert.ToInt32(new Random(DateTime.Now.Millisecond).Next(20000)));
                ctx.Person.Add(p);
                ctx.SaveChanges();
                pi.PersonId = p.PersonId;
                e.PersonId  = p.PersonId;
                ctx.Employee.Add(e);
                ctx.Pilot.Add(pi);
                ctx.SaveChanges();

                Console.WriteLine("Pilot #" + PNummer + ": " + Vorname + " " + Nachname);
            }

            CUI.PrintSuccess("Number of pilots: " + ctx.Pilot.Count());
        }
示例#19
0
        private static void PrintMigrationStatus(DbContext ctx)
        {
            CUI.H2("Getting Migration Status...");
            try
            {
                Dictionary <string, string> migrationsStatus = new Dictionary <string, string>();
                var migrations = ctx.Database.GetMigrationStatus();

                foreach (var item in migrations)
                {
                    if (item.Value)
                    {
                        CUI.Print(item.Key + ":" + " already applied", ConsoleColor.Green);
                    }
                    else
                    {
                        CUI.Print(item.Key + ":" + " TODO", ConsoleColor.Red);
                    }
                }
            }
            catch (Exception)
            {
                CUI.PrintError("Database not available!");
            }
        }
示例#20
0
        private static void Init_Passenger(WWWingsV1Context ctx)
        {
            Console.WriteLine("Create Passengers...");

            Random rnd2 = new Random();

            for (int PNummer = 1; PNummer <= NO_OF_PASSENGERS; PNummer++)
            {
                string Vorname = Firstnames[rnd2.Next(0, Firstnames.Length - 1)];
                ;
                string Nachname = Surnames[rnd2.Next(0, Surnames.Length - 1)];
                ;
                Passenger pas = new Passenger();

                Person p = new Person();
                //  p.ID = 1;
                p.Surname   = Nachname;
                p.GivenName = Vorname;
                p.Birthday  =
                    new DateTime(1940, 1, 1).AddDays(Convert.ToInt32(new Random(DateTime.Now.Millisecond).Next(20000)));
                pas.Person = p;

                pas.PassengerStatus = "A";
                ctx.Passenger.Add(pas);
                ctx.SaveChanges();

                if (PNummer % 100 == 0)
                {
                    Console.WriteLine("Passenger #" + PNummer + ": " + Vorname + " " + Nachname);
                }
            }
            CUI.PrintSuccess("Number of passengers: " + ctx.Passenger.Count());
        }
        public static void GroupBy1()
        {
            CUI.MainHeadline(nameof(GroupBy1));

            // Simple Group by: Min, Max, Sum und Average of FreeSeats per Destination
            using (var ctx = new WWWingsContext())
            {
                Console.WriteLine(ctx.Database.GetType().FullName);
                ctx.Log();

                var groups1 = (from p in ctx.FlightSet
                               group p by p.Departure into g
                               select new { City = g.Key, Min = g.Min(x => x.FreeSeats), Max = g.Max(x => x.FreeSeats), Sum = g.Sum(x => x.FreeSeats), Avg = g.Average(x => x.FreeSeats) });
                var count1 = groups1.Count();
                Console.WriteLine("Number of groups: " + count1);
                if (count1 > 0)
                {
                    // Second roundtrip to the database
                    foreach (var g in groups1.ToList())
                    {
                        Console.WriteLine(g.City + ": Min=" + g.Min + " / Max=" + g.Max + " / Avergae" + g.Avg + " / Sum:" + g.Sum);
                    }
                }
            }
        }
示例#22
0
        public static void LINQ_QueryWithPaging()
        {
            CUI.MainHeadline(nameof(LINQ_QueryWithPaging));
            string   name = "Müller";
            DateTime date = new DateTime(1972, 1, 1);

            // Create context instance
            using (var ctx = new WWWingsContext())
            {
                // Define query and execute
                var flightSet = (from f in ctx.FlightSet
                                 where f.FreeSeats > 0 &&
                                 f.BookingSet.Count > 0 &&
                                 f.BookingSet.Any(b => b.Passenger.Surname == name) &&
                                 f.Pilot.Birthday < date &&
                                 f.Copilot != null
                                 select f).Skip(5).Take(10).ToList();

                // Count number of loaded objects
                var c = flightSet.Count;
                Console.WriteLine("Number of found flights: " + c);

                // Print objects
                foreach (var f in flightSet)
                {
                    Console.WriteLine($"Flight Nr {f.FlightNo} from {f.Departure} to {f.Destination} has {f.FreeSeats} free seats!");
                }
            } // End using-Block -> Dispose()
        }
        public static void GroupBy3()
        {
            CUI.MainHeadline(nameof(GroupBy3));
            #region nested Groupy by
            using (var ctx = new WWWingsContext())
            {
                //ctx.Log();

                var groupSet = (from p in ctx.FlightSet
                                orderby p.FreeSeats
                                group p by p.Departure into g
                                select g);

                Console.WriteLine("Number of groups: " + groupSet.Count());

                foreach (var g in groupSet)
                {
                    Console.WriteLine(g.Key + ": " + g.Count());
                    foreach (var f in g)
                    {
                        // do something...
                        // Console.WriteLine("   " + f.FlightNo);
                    }
                }
            }
            #endregion
        }
示例#24
0
        public static void Projection_Read()
        {
            CUI.MainHeadline(nameof(Projection_Read));
            using (var ctx = new WWWingsContext())
            {
                var query = from f in ctx.FlightSet
                            where f.FlightNo > 100 && f.FlightNo < 200
                            orderby f.FlightNo
                            select new Flight()
                {
                    FlightNo    = f.FlightNo,
                    Date        = f.Date,
                    Departure   = f.Departure,
                    Destination = f.Destination,
                    FreeSeats   = f.FreeSeats
                };

                var flightSet = query.ToList();

                foreach (var f in flightSet)
                {
                    Console.WriteLine($"Flight Nr {f.FlightNo} from {f.Departure} to {f.Destination} has {f.FreeSeats} free seats!");
                }
            }
        }
示例#25
0
        public static async void AsyncForeach()
        {
            CUI.MainHeadline("Start " + nameof(AsyncForeach));
            WWWingsContext ctx = new WWWingsContext();

            // Define query
            var query = (from f in ctx.FlightSet.Include(p => p.BookingSet).ThenInclude(b => b.Passenger) where f.Departure == "Rome" && f.FreeSeats > 0 select f).Take(1);

            // Executing und iterate query with ForEachAsync
            CUI.PrintWithThreadID("Print objects");
            await query.ForEachAsync(async flight =>
            {
                // Print results
                CUI.PrintWithThreadID("Flight: " + flight.FlightNo + " from " + flight.Departure + " to " + flight.Destination + " has " + flight.FreeSeats + " free Seats");

                foreach (var p in flight.BookingSet)
                {
                    CUI.PrintWithThreadID(" Passenger: " + p.Passenger.GivenName + " " + p.Passenger.Surname);
                }

                // Save changes to each flight object within the loop
                //TODO: not possible wih EFCore 2.1.1 --> "New transaction is not allowed because there are other threads running in the session."
                //  CUI.PrintWithThreadID("  Start saving");
                //  flight.FreeSeats--;
                //await ctx.SaveChangesAsync();
                //CUI.PrintWithThreadID("   Changes saved!");

                //not possible wih EFCore 2.0: var count  = await ctx.SaveChangesAsync(); --> "New transaction is not allowed because there are other threads running in the session."
            });

            CUI.Print("End " + nameof(AsyncForeach));
        }
示例#26
0
 public static void EFPlus_FutureQuery()
 {
     CUI.MainHeadline(nameof(EFPlus_FutureQuery));
     using (var ctx = new DA.WWWingsContext())
     {
         ctx.Log();
         CUI.Headline("Define three future queries ... nothing happens in the database");
         QueryFutureEnumerable <Pilot>  qAllePilots      = ctx.PilotSet.Future();
         QueryFutureEnumerable <Flight> qflightSetRome   = ctx.FlightSet.Where(x => x.Departure == "Rome").Future();
         QueryFutureEnumerable <Flight> qFlightSetBerlin = ctx.FlightSet.Where(x => x.Departure == "Berlin").Future();
         CUI.Headline("Access the pilots:");
         var allePilots = qAllePilots.ToList();
         Console.WriteLine(allePilots.Count + " Pilots are loaded!");
         CUI.Headline("Access the flights from Rome:");
         var flightSetRom = qflightSetRome.ToList();
         Console.WriteLine(flightSetRom.Count + " flights from Berlin are loaded!");
         CUI.Headline("Define another two future queries ... nothing happens in the database");
         QueryFutureEnumerable <Flight> qFugSetLondon   = ctx.FlightSet.Where(x => x.Departure == "London").Future();
         QueryFutureEnumerable <Flight> qflightSetParis = ctx.FlightSet.Where(x => x.Departure == "Paris").Future();
         CUI.Headline("Access the flights from Berlin:");
         var flightSetBerlin = qFlightSetBerlin.ToList();
         Console.WriteLine(flightSetBerlin.Count + " flights from Rome are loaded!");
         CUI.Headline("Access the flights from London:");
         var flightSetLondon = qFugSetLondon.ToList();
         Console.WriteLine(flightSetLondon.Count + " flights from London are loaded!");
         CUI.Headline("Access the flights from Paris:");
         var flightSetParis = qflightSetParis.ToList();
         Console.WriteLine(flightSetParis.Count + " flights from Paris are loaded!");
     }
 }
        public static void Run()
        {
            CUI.MainHeadline(nameof(DEMO_AutoIncrement));
            using (var ctx = new Context())
            {
                CUI.Print("Database: " + ctx.Database.GetDbConnection().ConnectionString);

                var e = ctx.Database.EnsureCreated();

                if (e)
                {
                    CUI.Print("Database has been created!");
                }
                else
                {
                    CUI.Print("Database exists!");
                }

                CUI.Headline("Master");
                var obj2 = new Master1();
                foreach (var p in ctx.Entry(obj2).Properties)
                {
                    Console.WriteLine(p.Metadata.Name + ": " + p.Metadata.ValueGenerated);
                }
            }
        }
示例#28
0
 public void DrawHeader()
 {
     // Draw Header
     CUI.SetArea(1, 0, Console.WindowWidth, 1);
     CUI.DrawString("IP: " + localAddress + "   Port: " + receiver.Port);
     //			CUI.DrawString (16, 0, "Subnet: " + localSubnet);
 }
示例#29
0
        public static void Demo_ExplizitLoadingCustom()
        {
            CUI.MainHeadline(nameof(Demo_ExplizitLoadingCustom));

            var ctx = new WWWingsContext();

            ctx.PassengerSet.ToList();

            var flightSet = (from f in ctx.FlightSet
                             where f.Departure.StartsWith("M")
                             select f)
                            .ToList();

            var flight = flightSet.ElementAt(0);

            Console.WriteLine(flight.ToString());

            // Explicit reloading all pilots
            ctx.PilotSet.ToList();
            Console.WriteLine("Pilot: " + flight.Pilot.FullName);
            foreach (var f in flightSet.Take(10))
            {
                Console.WriteLine(f.ToString());
                ctx.PilotSet.Where(x => x.FlightAsPilotSet.Any(y => y.FlightNo == f.FlightNo)).ToList();
                Console.WriteLine("Number of Passengers on this Flight: " + f.BookingSet.Count);
                Console.WriteLine("Pilot: " + f.Pilot.FullName);
            }
        }
        public static void ComputedColumnWithFormula()
        {
            CUI.MainHeadline(nameof(ComputedColumnWithFormula));

            int flightNo = 101;

            using (WWWingsContext ctx = new WWWingsContext())
            {
                ctx.Log();
                var flight = ctx.FlightSet.Find(flightNo);
                Console.WriteLine($"BEFORE: {flight}: Utilization={flight.Utilization:##0.00}%");

                flight.FreeSeats -= 10;
                //not possible: flight.Utilization = 100;

                // The change is not yet visible in the Utilization, since the Utilization is calculated in the DBMS
                Console.WriteLine($"After changes: {flight}: Utilization={flight.Utilization:##0.00}%");

                ctx.SaveChanges();
                // The change in Utilization is now visible
                Console.WriteLine($"After saving: {flight}: Utilization={flight.Utilization:##0.00}%");

                CUI.Headline("Metadata of Flight properties");
                foreach (PropertyEntry p in ctx.Entry(flight).Properties)
                {
                    Console.WriteLine(p.Metadata.Name + ": " + p.Metadata.ValueGenerated);
                }
            }
        }