public static void ADONET_DataAdapter() { CUI.MainHeadline(nameof(ADONET_DataAdapter)); var connstring = new WWWingsContext().Database.GetDbConnection().ConnectionString; DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); SqlConnection connection = new SqlConnection(connstring); using (connection) { SqlDataAdapter adapter = new SqlDataAdapter( "SELECT * FROM dbo.Flight", connection); SqlCommandBuilder builder = new SqlCommandBuilder(adapter); Console.WriteLine(builder.GetUpdateCommand().CommandText); } }
public static void RelationshipFixUp_Case2() { CUI.MainHeadline(nameof(RelationshipFixUp_Case2)); void PrintPilot(Pilot pilot) { CUI.PrintSuccess(pilot.ToString()); if (pilot.FlightAsPilotSet != null) { Console.WriteLine("Flights of this pilot:"); foreach (var f in pilot.FlightAsPilotSet) { Console.WriteLine(f); } } else { CUI.PrintWarning("No flights!"); } } using (var ctx = new WWWingsContext()) { // Load a Pilot var pilot = ctx.PilotSet.FirstOrDefault(); // Print pilot and his flights PrintPilot(pilot); // Create a new flight for this pilot var flight = new Flight(); flight.Departure = "Berlin"; flight.Destination = "Berlin"; flight.Date = DateTime.Now.AddDays(10); flight.FlightNo = ctx.FlightSet.Max(x => x.FlightNo) + 1; flight.PilotId = pilot.PersonID; ctx.FlightSet.Add(flight); // this does not help: ctx.ChangeTracker.DetectChanges(); // Print pilot and his flights PrintPilot(pilot); // Print pilot of the new flight Console.WriteLine(flight.Pilot); } }
public static void RemoveFlightWithKey() { Console.WriteLine(nameof(RemoveFlightWithKey)); using (WWWingsContext ctx = new WWWingsContext()) { // Create a dummy object var f = new Flight(); f.FlightNo = 123456; Console.WriteLine($"After creation: Flight #{f.FlightNo}: {f.Departure}->{f.Destination} has {f.FreeSeats} free seats! State of the flight object: " + ctx.Entry(f).State); // Append dummy object to context ctx.Attach(f); Console.WriteLine($"After attach: Flight #{f.FlightNo}: {f.Departure}->{f.Destination} has {f.FreeSeats} free seats! State of the flight object: " + ctx.Entry(f).State); // Delete flight ctx.FlightSet.Remove(f); // or: ctx.Remove(f); Console.WriteLine($"After remove: 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 Demo_RelationhipFixup1N() { CUI.MainHeadline(nameof(Demo_RelationhipFixup1N)); using (var ctx = new WWWingsContext()) { // Load a flight var flight101 = ctx.FlightSet.SingleOrDefault(x => x.FlightNo == 101); Console.WriteLine($"Flight Nr {flight101.FlightNo} from {flight101.Departure} to {flight101.Destination} has {flight101.FreeSeats} free seats!"); // Load the pilot for this flight with the list of his flights var oldPilot = ctx.PilotSet.Include(x => x.FlightAsPilotSet).SingleOrDefault(x => x.PersonID == flight101.PilotId); Console.WriteLine("Pilot: " + oldPilot.PersonID + ": " + oldPilot.GivenName + " " + oldPilot.Surname + " has " + oldPilot.FlightAsPilotSet.Count + " flights as pilot!"); // Next pilot in the list load with the list of his flights var newPilot = ctx.PilotSet.Include(x => x.FlightAsPilotSet).SingleOrDefault(x => x.PersonID == flight101.PilotId + 1); Console.WriteLine("Planned Pilot: " + newPilot.PersonID + ": " + newPilot.GivenName + " " + newPilot.Surname + " has " + newPilot.FlightAsPilotSet.Count + " flights as pilot!"); // Assign to Flight CUI.Print("Assignment of the flight to the planned pilot...", ConsoleColor.Cyan); newPilot.FlightAsPilotSet.Add(flight101); // optional:force Relationship Fixup // ctx.ChangeTracker.DetectChanges(); CUI.Print("Output before saving: ", ConsoleColor.Cyan); Console.WriteLine("Old pilot: " + oldPilot.PersonID + ": " + oldPilot.GivenName + " " + oldPilot.Surname + " has " + oldPilot.FlightAsPilotSet.Count + " flights as a pilot!"); Console.WriteLine("New pilot: " + newPilot.PersonID + ": " + newPilot.GivenName + " " + newPilot.Surname + " has " + newPilot.FlightAsPilotSet.Count + " flights as a pilot!"); var pilotAktuell = flight101.Pilot; // Current Pilot in the Flight object Console.WriteLine("Pilot for flight " + flight101.FlightNo + " is currently: " + pilotAktuell.PersonID + ": " + pilotAktuell.GivenName + " " + pilotAktuell.Surname); // SaveChanges()() CUI.Print("Saving... ", ConsoleColor.Cyan); var count = ctx.SaveChanges(); CUI.MainHeadline("Number of saved changes: " + count); CUI.Print("Output after saving: ", ConsoleColor.Cyan); Console.WriteLine("Old Pilot: " + oldPilot.PersonID + ": " + oldPilot.GivenName + " " + oldPilot.Surname + " has " + oldPilot.FlightAsPilotSet.Count + " flights as pilot!"); Console.WriteLine("New Pilot: " + newPilot.PersonID + ": " + newPilot.GivenName + " " + newPilot.Surname + " has " + newPilot.FlightAsPilotSet.Count + " flights as pilot!"); pilotAktuell = flight101.Pilot; // Current pilot from the perspective of the Flight object Console.WriteLine("Pilot for Flight " + flight101.FlightNo + " is now: " + pilotAktuell.PersonID + ": " + pilotAktuell.GivenName + " " + pilotAktuell.Surname); } }
public static void Projection_EntityType() { using (var ctx = new WWWingsContext()) { CUI.MainHeadline(nameof(Projection_EntityType)); var q = (from f in ctx.FlightSet where f.FlightNo > 100 orderby f.FlightNo select new Flight() { FlightNo = f.FlightNo, Date = f.Date, Departure = f.Departure, Destination = f.Destination, FreeSeats = f.FreeSeats, Timestamp = f.Timestamp }).Take(2); var flightSet = q.ToList(); foreach (var f in flightSet) { Console.WriteLine($"Flight Nr {f.FlightNo} from {f.Departure} to {f.Destination} has {f.FreeSeats} free seats!"); } Console.WriteLine("Number of flights: " + flightSet.Count); foreach (var f in flightSet) { Console.WriteLine("Before attach: " + f + " State: " + ctx.Entry(f).State + " Timestamp: " + ByteArrayToString(f.Timestamp)); ctx.Attach(f); Console.WriteLine("After attach: " + f + " State: " + ctx.Entry(f).State + " Timestamp: " + ByteArrayToString(f.Timestamp)); f.FreeSeats--; Console.WriteLine("After Änderung: " + f + " State: " + ctx.Entry(f).State + " Timestamp: " + ByteArrayToString(f.Timestamp)); var count = ctx.SaveChanges(); Console.WriteLine("Number of saved changes: " + count); Console.WriteLine("After saving: " + f + " State: " + ctx.Entry(f).State + " Timestamp: " + ByteArrayToString(f.Timestamp)); } } }
public static void LINQ_ToString() { CUI.MainHeadline(nameof(LINQ_ToString)); using (var ctx = new WWWingsContext()) { ctx.Log(); var q1 = from p in ctx.FlightSet where p.FlightNo < 10 orderby p.FreeSeats select p; EntityQueryable <Flight> q1b = (EntityQueryable <Flight>)q1; Console.WriteLine(q1.ToString()); // EF: returns SQL. EFC: returns type :-( Console.WriteLine(q1b.ToString()); // EF: returns SQL. EFC: returns type :-( } }
public static void LINQ_Find() { CUI.MainHeadline(nameof(LINQ_Find)); using (var ctx = new WWWingsContext()) { ctx.FlightSet.ToList(); // Caching all flights in context (here as an example only to show the caching effect!) var flightNo = 101; var f = ctx.FlightSet.Find(flightNo); // Flight is loaded from cache! if (f != null) { Console.WriteLine($"Flight Nr {f.FlightNo} from {f.Departure} to {f.Destination} has {f.FreeSeats} free seats!"); } else { Console.WriteLine("Flight not found!"); } } // End using-Block -> Dispose() }
public static void GeneratedSQL() { CUI.MainHeadline(nameof(GeneratedSQL)); var ctx = new WWWingsContext(); var flightSet1 = ctx.FlightSet.ToList(); var flightSet2 = ctx.FlightSet.Where(f2 => f2.Departure == "Rome").ToList(); var flightSet3 = (from f3 in ctx.FlightSet where f3.Departure.StartsWith("M") select f3) .ToList(); var flightSet4 = (from f4 in ctx.FlightSet where f4.Departure.StartsWith("M") orderby f4.FlightNo select f4).Skip(5).Take(10).ToList(); }
public static void TrackGraph() { CUI.MainHeadline(nameof(TrackGraph)); Flight f; using (WWWingsContext ctx1 = new WWWingsContext()) { int flightNo = 150; f = ctx1.FlightSet.Include(x => x.Pilot).Where(x => x.FlightNo == flightNo).SingleOrDefault(); Console.WriteLine(f); Console.WriteLine(f.Pilot); } using (WWWingsContext ctx2 = new WWWingsContext()) { ctx2.ChangeTracker.TrackGraph(f, TrackGraph_Callback); var anz = ctx2.SaveChanges(); Console.WriteLine(anz + " Changes saved!"); } }
public static void Kontextwechselproblem() { Flight flight101; using (var ctx1 = new WWWingsContext()) { // Lade einen Flight flight101 = ctx1.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! Pilot: " + flight101.Pilot); } using (var ctx2 = new WWWingsContext()) { // Lade einen Flight var pilot = ctx2.PilotSet.Find(flight101.PilotId + 1); flight101.Pilot = pilot; Console.WriteLine("Neuer Pilot: " + pilot.ToString()); var count = ctx2.SaveChanges(); Console.WriteLine(count + " Changes saved!"); } }
private void C_Test_Click(object sender, RoutedEventArgs e) { try { ctx = new WWWingsContext(); var flight = ctx.FlightSet.FirstOrDefault(); if (flight == null) { MessageBox.Show("No flights :-(", "Test Connection", MessageBoxButton.OK, MessageBoxImage.Warning); } else { MessageBox.Show("OK!", "Test Connection", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), "Test Connection", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Variante 3 UNSINNIG !!! /// Wenn Concurrency Check nicht auf Timestamp, sondern auf Wertespalten (außer Timestamp) aktiv, gehen Varianten 1 und 2 nicht, weil EF die neuen Werte auch als Originalwerte annehmen wird und die nicht in DB finden kann /// Hier wird aber fehlerhafterweise der Inhalt der DB nochmal gelesen, weil den Concurreny Check absurd macht /// </summary> public static void Detached_Flight_ConcurrencyCheck_AusDB() { CUI.MainHeadline(nameof(Detached_Flight_ConcurrencyCheck_AusDB)); Flight flight; CUI.Print("Lade Objekt in Kontextinstanz #1"); using (WWWingsContext ctx1 = new WWWingsContext()) { ctx1.Log(); //ctx1.Configuration.LazyLoadingEnabled = false; flight = ctx1.FlightSet.Find(110); } CUI.Print("Objekt ändern"); CUI.Print(flight.ToString()); flight.FreeSeats--; flight.Date = flight.Date.AddHours(2); CUI.Print(flight.ToString()); CUI.Print("Objekt nun speichern mit Kontextinstanz #2"); using (WWWingsContext ctx2 = new WWWingsContext()) { ctx2.Log(); // Wegen des Concurreny Checks brauchen wir die Originalwerte entweder aus dem Objekt selbst oder der DB // Aus DB ist aber keine gute Lösung, denn damit ist der Concurreny Check auf den Spalten unsinnig // hier aus DB var flightOrg = ctx2.FlightSet.Find(110); CUI.Print(ctx2.Entry(flightOrg).State.ToString()); // Nun Werte des alten Objekts auf das neue kopieren ctx2.Entry(flightOrg).CurrentValues.SetValues(flight); CUI.Print(ctx2.Entry(flightOrg).State.ToString()); var count = ctx2.SaveChanges(); Console.WriteLine("Saved changes: " + count.ToString()); if (count != 1) { Debugger.Break(); } } }
public static void GetFlight_StandardCache_Aendern(string departure = "Rome") { using (var ctx = new WWWingsContext()) { ctx.Log(); CUI.Headline($"Alle Flights from {departure} laden!"); // Alle Flights laden var flightSet = ctx.FlightSet.Where(x => x.Departure == departure && x.FlightNo < 200).ToList(); var flightNo = 190; // FlightSet 190 ist ein FlightSet from Rom, der schon geladen wurde // flightSet.ElementAt // Ein Objekt wird im RAM geändert var flightSetImRAM = flightSet.FirstOrDefault(x => x.FlightNo == flightNo); CUI.Print("FlightSet Before changes: " + flightSetImRAM?.ToShortString(), ConsoleColor.White); flightSetImRAM.FreeSeats--; CUI.Print("FlightSet to der Änderung: " + flightSetImRAM?.ToShortString(), ConsoleColor.White); // Dann wird das Objekt neu geladen! CUI.Headline("Ein FlightSet laden mit Find() - allein aus Cache!"); var flight1 = ctx.FlightSet.Find(flightNo); CUI.Print(flight1?.ToShortString(), ConsoleColor.White); CUI.Headline("Ein FlightSet laden mit SingleOrDefault() -> Query!"); var flight2 = ctx.FlightSet.SingleOrDefault(x => x.FlightNo == flightNo); CUI.Print(flight2?.ToShortString(), ConsoleColor.White); CUI.Headline("Ein FlightSet laden mit FirstOrDefault() -> Query!"); var flight3 = ctx.FlightSet.FirstOrDefault(x => x.FlightNo == flightNo); CUI.Print(flight3?.ToShortString(), ConsoleColor.White); CUI.Headline("Ein FlightSet laden mit where/SingleOrDefault() -> Query!"); var flight4 = ctx.FlightSet.Where(x => x.FlightNo == flightNo).SingleOrDefault(); CUI.Print(flight4.ToShortString(), ConsoleColor.White); CUI.Headline("Cacheinhalt"); foreach (var f in ctx.FlightSet.Local) { Console.WriteLine(f.ToShortString()); } } }
public static void Demo_EagerLoading() { CUI.MainHeadline(nameof(Demo_EagerLoading)); using (var ctx = new WWWingsContext()) { var flightNo = 101; // Load the flight and some connected objects via Eager Loading var f = ctx.FlightSet .Include(b => b.BookingSet).ThenInclude(p => p.Passenger) .Include(b => b.Pilot).ThenInclude(p => p.FlightAsPilotSet) .Include(b => b.Copilot).ThenInclude(p => p.FlightAsCopilotSet) .SingleOrDefault(x => x.FlightNo == flightNo); Console.WriteLine($"Flight Nr {f.FlightNo} from {f.Departure} to {f.Destination} has {f.FreeSeats} free seats!"); if (f.Pilot != null) { Console.WriteLine($"Pilot: {f.Pilot.Surname} has {f.Pilot.FlightAsPilotSet.Count} flights as a pilot!"); } else { Console.WriteLine("No pilot assigned!"); } if (f.Copilot != null) { Console.WriteLine($"Copilot: {f.Copilot.Surname} has {f.Copilot.FlightAsCopilotSet.Count} flights as a Copilot!"); } else { Console.WriteLine("No Copilot assigned!"); } Console.WriteLine("Number of passengers on this flight: " + f.BookingSet.Count); Console.WriteLine("Passengers on this flight:"); foreach (var b in f.BookingSet) { Console.WriteLine("- Passenger #{0}: {1} {2}", b.Passenger.PersonID, b.Passenger.GivenName, b.Passenger.Surname); } } }
public static void TrackingMode_QueryTrackingBehavior() { CUI.MainHeadline("Default setting: TrackAll. Use AsNoTracking()"); using (WWWingsContext ctx = new WWWingsContext()) { ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.TrackAll; // is default var flightSet = ctx.FlightSet.AsNoTracking().ToList(); var flight = flightSet[0]; Console.WriteLine(flight + " object state: " + ctx.Entry(flight).State); // Detached flight.FreeSeats--; Console.WriteLine(flight + " object state: " + ctx.Entry(flight).State); // Detached int count = ctx.SaveChanges(); Console.WriteLine($"Saved changes: {count}"); // 1 } CUI.MainHeadline("Default setting: NoTracking."); using (WWWingsContext ctx = new WWWingsContext()) { ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; // NoTracking var flightSet = ctx.FlightSet.ToList(); var flight = flightSet[0]; Console.WriteLine(flight + " object state: " + ctx.Entry(flight).State); // Detached flight.FreeSeats--; Console.WriteLine(flight + " object state: " + ctx.Entry(flight).State); // Detached int count = ctx.SaveChanges(); Console.WriteLine($"Saved changes: {count}"); // 1 } CUI.MainHeadline("Default setting: NoTracking. Use AsTracking()"); using (WWWingsContext ctx = new WWWingsContext()) { ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; // NoTracking var flightSet = ctx.FlightSet.AsTracking().ToList(); var flight = flightSet[0]; Console.WriteLine(flight + " object state: " + ctx.Entry(flight).State); // Unchanged flight.FreeSeats--; Console.WriteLine(flight + " object state: " + ctx.Entry(flight).State); // Modified int count = ctx.SaveChanges(); Console.WriteLine($"Saved changes: {count}"); // 1 } }
public static void LINQ_SingleOrDefault() { CUI.MainHeadline(nameof(LINQ_SingleOrDefault)); using (var ctx = new WWWingsContext()) { var flightNo = 101; var f = (from x in ctx.FlightSet where x.FlightNo == flightNo select x).SingleOrDefault(); if (f != null) { Console.WriteLine($"Flight Nr {f.FlightNo} from {f.Departure} to {f.Destination} has {f.FreeSeats} free seats!"); } else { Console.WriteLine("Flight not found!"); } } // End using-Block -> Dispose() }
public static void EreignisFolge() { var ctx1 = new WWWingsContext(); CUI.Print("1. Kontext 1. Abfrage"); ctx1.FlightSet.FirstOrDefault(); CUI.Print("1. Kontext 2. Abfrage"); ctx1.FlightSet.FirstOrDefault(); var ctx2 = new WWWingsContext(); CUI.Print("2. Kontext 1. Abfrage"); ctx2.FlightSet.FirstOrDefault(); CUI.Print("2. Kontext 2. Abfrage"); ctx2.FlightSet.FirstOrDefault(); var ctx3 = new WWWingsContext(); CUI.Print("3. Kontext 1. Abfrage"); ctx3.FlightSet.FirstOrDefault(); CUI.Print("3. Kontext 2. Abfrage"); ctx3.FlightSet.FirstOrDefault(); }
public static void ClearCache() { using (var ctx = new WWWingsContext()) { ctx.Log(); CUI.Headline("Load 5 Flights and Pilots..."); ctx.FlightSet.Take(5).ToList(); ctx.PilotSet.Take(5).ToList(); Console.WriteLine("Flights in Cache: " + ctx.FlightSet.Local.Count); Console.WriteLine("Pilots in Cache: " + ctx.PilotSet.Local.Count); foreach (var f in ctx.FlightSet.Local.ToList()) { ctx.Entry(f).State = EntityState.Detached; } Console.WriteLine("Flights in Cache: " + ctx.FlightSet.Local.Count); Console.WriteLine("Pilots in Cache: " + ctx.PilotSet.Local.Count); } }
public static void BulkDeleteEFCAPIwithBatching() { CUI.Headline(nameof(BulkDeleteEFCAPIwithBatching)); int total = 0; var sw = new Stopwatch(); sw.Start(); using (var ctx = new WWWingsContext()) { var min = 20000; var flightSet = ctx.FlightSet.Where(x => x.FlightNo >= min).ToList(); foreach (Flight f in flightSet) { ctx.FlightSet.Remove(f); } total = ctx.SaveChanges(); } sw.Stop(); Console.WriteLine("Number of DELETE statements: " + total); Console.WriteLine("Duration: " + sw.ElapsedMilliseconds); }
public static void LINQ_CustomFunction() { CUI.MainHeadline("Query with Custom Function - RAM :-("); using (var ctx = new WWWingsContext()) { var q4 = from f in ctx.FlightSet where f.FreeSeats > 0 && GetNumberOfDaysUntil(f.Date) > 10 orderby f.FlightNo select f; List <Flight> l4 = q4.Take(10).ToList(); Console.WriteLine("Count: " + l4.Count); foreach (var f in l4) { Console.WriteLine(f); } } }
public static void TransactionScopeDemo() { CUI.Headline(nameof(TransactionScopeDemo)); using (var t = new TransactionScope()) { using (var ctx1 = new WWWingsContext()) { int flightNo = ctx1.FlightSet.OrderBy(x => x.FlightNo).FirstOrDefault().FlightNo; var f = ctx1.FlightSet.Where(x => x.FlightNo == flightNo).SingleOrDefault(); Console.WriteLine("Before: " + f.ToString()); f.FreeSeats--; f.Memo = "Last changed at " + DateTime.Now.ToString(); Console.WriteLine("After: " + f.ToString()); var count1 = ctx1.SaveChanges(); Console.WriteLine("Number of saved changes: " + count1); } using (var ctx2 = new WWWingsContext()) { var f = ctx2.FlightSet.OrderBy(x => x.FlightNo).Skip(1).Take(1).SingleOrDefault(); Console.WriteLine("Before: " + f.ToString()); f.FreeSeats--; f.Memo = "Last changed at " + DateTime.Now.ToString(); Console.WriteLine("After: " + f.ToString()); var count1 = ctx2.SaveChanges(); Console.WriteLine("Number of saved changes: " + count1); } // Commit Transaction! t.Complete(); CUI.PrintSuccess("Completed!"); } }
public static void GroupBy_SQL_NonEntityType() { // Get the number of flights per Departure using (var ctx = new WWWingsContext()) { // Map SQL to non-entity class Console.WriteLine(ctx.Database.GetType().FullName); ctx.Log(); var sql = "SELECT Departure, COUNT(FlightNo) AS FlightCount FROM Flight GROUP BY Departure"; // ERROR!!! Cannot create a DbSet for 'Group' because this type is not included in the model for the context." var groupSet = ctx.Set <DepartureGroup>().FromSql(sql); // Output foreach (var g in groupSet) { Console.WriteLine(g.Departure + ": " + g.FlightCount); } } return; // Groupy by "nested" 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("Count: " + groupSet.Count()); foreach (var g in groupSet) { Console.WriteLine(g.Key + ": " + g.Count()); foreach (var f in g) { Console.WriteLine(" " + f.FlightNo); } } } }
public static void RelationshipFixup_Run() { CUI.Headline("RelationshipFixup/First Level Cache"); using (WWWingsContext ctx = new WWWingsContext()) { ctx.Log(); var pilot = ctx.PilotSet.Find(1030); Console.WriteLine("Pilot: " + pilot.PersonID); pilot = null; // Möglich: Löschen aus Cache // ctx.Pilot.Local.Clear(); somit würde es wirklich weg sein! // or: ctx.Pilot.Local.Remove(pilot); VOR DEM SETZEN AUF NULL! // der Pilot sollte nun weg sein var flight = ctx.FlightSet.Find(101); // ist er aber nicht !!! Console.WriteLine(flight); Console.WriteLine("Pilot dieses flightSets: " + flight.Pilot.PersonID); } }
public static void ShowUpdatedTimeStamp() { CUI.MainHeadline(nameof(ShowUpdatedTimeStamp)); using (WWWingsContext ctx = new WWWingsContext()) { var f = ctx.FlightSet.Take(1).SingleOrDefault(); Console.WriteLine("Before: " + f.ToString() + " Timestamp: " + f.Timestamp.ByteArrayToString()); f.FreeSeats--; // Change #1 Console.WriteLine("After change: " + f.ToString() + " Timestamp: " + f.Timestamp.ByteArrayToString()); var anz1 = ctx.SaveChanges(); Console.WriteLine("After saving: " + f.ToString() + " Timestamp: " + f.Timestamp.ByteArrayToString()); CUI.PrintSuccess("Number of saved changes: " + anz1); Console.WriteLine("Before: " + f.ToString() + " Timestamp: " + f.Timestamp.ByteArrayToString()); f.FreeSeats--; // Change #2 Console.WriteLine("After change: " + f.ToString() + " Timestamp: " + f.Timestamp.ByteArrayToString()); var anz2 = ctx.SaveChanges(); Console.WriteLine("After saving: " + f.ToString() + " Timestamp: " + f.Timestamp.ByteArrayToString()); CUI.PrintSuccess("Number of saved changes: " + anz2); } }
public static void Demo_PreLoadingPilotsCaching() { CUI.MainHeadline(nameof(Demo_PreLoadingPilotsCaching)); using (var ctx = new WWWingsContext()) { // 1. Load ALL pilots ctx.PilotSet.ToList(); // 2. Load only several flights. The Pilot and Copilot object will then be available for every flight! var flightNoListe = new List <int>() { 101, 117, 119, 118 }; foreach (var flightNo in flightNoListe) { var f = ctx.FlightSet .SingleOrDefault(x => x.FlightNo == flightNo); Console.WriteLine($"Flight Nr {f.FlightNo} from {f.Departure} to {f.Destination} has {f.FreeSeats} free seats!"); if (f.Pilot != null) { Console.WriteLine($"Pilot: {f.Pilot.Surname} has {f.Pilot.FlightAsPilotSet.Count} flights as pilot!"); } else { Console.WriteLine("No pilot assigned!"); } if (f.Copilot != null) { Console.WriteLine($"Copilot: {f.Copilot.Surname} has {f.Copilot.FlightAsCopilotSet.Count} flights as copilot!"); } else { Console.WriteLine("No copilot assigned!"); } } } }
public static void Demo1_PilotBleibtImRAM() { CUI.Headline("RelationshipFixup/First Level Cache"); int flightNo = 101; int pilotID = 0; // Vorspiel: passende PilotID ermittelt using (var ctx = new WWWingsContext()) { pilotID = ctx.FlightSet.Include(f => f.Pilot).SingleOrDefault(f => f.FlightNo == flightNo).PilotId; } using (var ctx = new WWWingsContext()) { var pilot = ctx.PilotSet.AsNoTracking().SingleOrDefault(x => x.PersonID == pilotID); Console.WriteLine("--- Navigationseigenschaften-Mengentypen"); Console.WriteLine(pilot.FlightAsPilotSet?.Count + " FlightAsPilotSet: " + pilot.FlightAsPilotSet?.GetType().FullName); Console.WriteLine(pilot.FlightAsCopilotSet?.Count + " FlightAsCopilotSet: " + pilot.FlightAsCopilotSet?.GetType().FullName); Console.WriteLine("Pilot: " + pilot); pilot = null; // der Pilot sollte nun weg sein var flight = ctx.FlightSet.Include(f => f.Pilot).SingleOrDefault(f => f.FlightNo == flightNo); Console.WriteLine(flight); Console.WriteLine(flight.Pilot); if (flight.Pilot != null) { CUI.PrintSuccess("Fixup OK!"); } else { CUI.PrintError("Fixup geht nicht!"); } } }
public static void RemoveFlight() { CUI.MainHeadline(nameof(RemoveFlight)); using (WWWingsContext ctx = new WWWingsContext()) { var f = ctx.FlightSet.SingleOrDefault(x => x.FlightNo == 123456); if (f == null) { return; } 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); // Remove flight ctx.FlightSet.Remove(f); // or: ctx.Remove(f); Console.WriteLine($"After deleting: 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 EF_ChangeTracking() { CUI.MainHeadline(nameof(EF_ChangeTracking)); using (WWWingsContext ctx = new WWWingsContext()) { // kommt in nächster Version //ctx.Configuration.AutoDetectChangesEnabled = false; var f = ctx.FlightSet.FirstOrDefault(); Console.WriteLine("Before: " + f.ToString()); //Änderung f.FreeSeats = (short)(new Random(DateTime.Now.Millisecond).Next(1, 100)); Console.WriteLine("After: " + f.ToString()); EFC_Util.PrintChangeInfo(ctx); var anz = ctx.SaveChanges(); Console.WriteLine("Anzahl gespeicherter Ändeurngen: " + anz); } }
/// <summary> /// Nur geänderte Spalten zurückschreiben /// Attach()/IsModified=true /// achtung: Geht nicht wenn Concurrency Check auf FreeSeats, da da EF den neuen Wert auch als alten Wert annimmt! /// </summary> public static void Detached_Flight_EinzelneProperties() { CUI.MainHeadline(nameof(Detached_Flight_EinzelneProperties)); Flight flight; CUI.Print("Lade Objekt in Kontextinstanz #1"); using (WWWingsContext ctx1 = new WWWingsContext()) { ctx1.Log(); //ctx1.Configuration.LazyLoadingEnabled = false; flight = ctx1.FlightSet.Find(110); } CUI.Print("Objekt ändern"); CUI.Print(flight.ToString()); flight.Memo = "last changed at " + DateTime.Now; flight.FreeSeats--; CUI.Print(flight.ToString()); CUI.Print("Objekt nun speichern mit Kontextinstanz #2"); using (WWWingsContext ctx2 = new WWWingsContext()) { ctx2.Log(); ctx2.FlightSet.Attach(flight); CUI.Print(ctx2.Entry(flight).State.ToString()); // Zustand einzelner Properties ändern ctx2.Entry(flight).Property(x => x.Memo).IsModified = true; ctx2.Entry(flight).Property(x => x.FreeSeats).IsModified = true; CUI.Print(ctx2.Entry(flight).State.ToString()); var count = ctx2.SaveChanges(); Console.WriteLine("Saved changes: " + count.ToString()); if (count != 1) { Debugger.Break(); } } }
public static void Demo_PreLoading1() { CUI.MainHeadline(nameof(Demo_PreLoading1)); var ctx = new WWWingsContext(); // Pre-Loading all pilots var piotenSet = ctx.PilotSet.ToList(); Console.WriteLine("Anzahl Pilots: " + piotenSet.Count); //ctx.PassengerSet.ToList(); // Now load some flights var flightSet = ctx.FlightSet.Take(10).ToList(); var flight = flightSet.ElementAt(0); Console.WriteLine(flight.ToString()); //Console.WriteLine("Number of passengers on this flight: " + flight.PassengerSet.Count); if (flight.Pilot != null) { Console.WriteLine("Pilot: " + flight.Pilot.FullName); } else { Debugger.Break(); } foreach (var f in flightSet.Take(10)) { Console.WriteLine(f.ToString()); //Console.WriteLine("Number of passengers on this flight: " + f.PassengerSet.Count); if (flight.Pilot != null) { Console.WriteLine("Pilot: " + f.Pilot.FullName); } } }