private static void ConcurrentTest() { using (var context1 = new BikeRentalContext()) using (var context2 = new BikeRentalContext()) { var user1 = context1.Users.Find(1); user1.PhoneNumber = "555-555-555"; var user2 = context2.Users.Find(1); user2.PhoneNumber = "777-777-777"; // Different order context2.SaveChanges(); // Some longer break, just for demo purpose - coffee break Thread.Sleep(5000); try { context1.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { WriteLine("Hey man, your coffee caused an exception"); var entry = ex.Entries.Single(); entry.Reload(); entry.Entity.Dump("Somebody has just saved the following user:"); } } }
public void DistributedTransactionScope() { // System.Transactions using (var transaction = new TransactionScope()) { var user = new User { FirstName = "Janusz", Discount = 40, PhoneNumber = "111-222-333", Parameters = new Parameters { P1 = 123, P2 = 345 } }; using (var firstContext = new BikeRentalContext()) { firstContext.Users.Add(user); firstContext.SaveChanges(); } using (var secondContext = new BikeRentalContext()) { secondContext.Users.Add(user); secondContext.SaveChanges(); } // Set transaction flag ONLY. Changes are not commited. transaction.Complete(); } }
private static void ConcurrentWithRowVersionTest() { using (var context1 = new BikeRentalContext()) using (var context2 = new BikeRentalContext()) { var station1 = context1.Stations.Find(1); station1.Name = "Cmc"; var station2 = context2.Stations.Find(1); station2.Name = "Lmc"; // Different order context2.SaveChanges(); // Some longer break, just for demo purpose - coffee break Thread.Sleep(5000); try { context1.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { WriteLine("Hey man, your coffee caused an exception"); var entry = ex.Entries.Single(); entry.Reload(); entry.Entity.Dump("Somebody has just saved the following station:"); } } }
private static void AddVehiclesTest() { using (var context = new BikeRentalContext()) { var bike = new Bike { BikeType = BikeType.City, Color = "red", Number = "B005" }; var bike2 = new Bike { BikeType = BikeType.Moutain, Color = "yellow", Number = "B006" }; var scooter = new Scooter { Color = "yellow", Number = "S001", EngineCapacity = 100 }; context.Vehicles.Add(bike); context.Vehicles.Add(bike2); context.Vehicles.Add(scooter); context.SaveChanges(); } }
private static void AddUser(string name, int discount) { var user = new User { FirstName = name, LastName = $"N_{DateTime.Now.Hour}_{DateTime.Now.Minute}", Discount = discount, PhoneNumber = "123123123", Parameters = new Parameters { P1 = DateTime.Now.Minute, P2 = DateTime.Now.Millisecond } }; using (var dbContext = new BikeRentalContext()) { try { dbContext.Users.Add(user); dbContext.SaveChanges(); } catch (Exception exception) { throw; } } }
private static void ExecuteSpTest() { var proc = @" create procedure uspDeleteBike(@BikeId int) as begin delete from [rentals].[Vehicles] where [VehicleId] = @BikeId; end "; using (var context = new BikeRentalContext()) { context.Bikes.Add(new Bike { BikeType = BikeType.City, Color = "Test", Number = "B123" }); context.SaveChanges(); context.Bikes.ToList().Dump(); var bikeToDelete = context.Bikes.FirstOrDefault(x => x.Number == "B123"); if (bikeToDelete != null) { var idParameter = new SqlParameter("BikeId", bikeToDelete.VehicleId); context.Database.ExecuteSqlCommand("uspDeleteBike @BikeId", idParameter); context.SaveChanges(); context.Bikes.ToList().Dump(); } } }
public void StorageTest() { // // To enable automatic storage procedures there is a need to configure object: // MapToStoredProcedures(); // using (var context = new BikeRentalContext()) { var station = new Station() { Address = "jakis adres", Name = "stacjaX", Location = new Location { Latitude = 1, Longitude = 1 } }; context.Stations.Add(station); try { context.SaveChanges(); } catch (System.Exception exception) { throw; } } }
private static void AddStations(int count) { var stations = new List <Station>(); for (int i = 0; i < count; i++) { var station = new Station { Name = $"Stacja_{i}", Address = $"Adres_{i}_{DateTime.Now.Hour}_{DateTime.Now.Minute}", Location = new Location { Latitude = DateTime.Now.Millisecond, Longitude = DateTime.Now.Millisecond }, Capacity = 10, IsActive = true }; stations.Add(station); } using (var dbContext = new BikeRentalContext()) { dbContext.Database.Exists(); dbContext.Stations.AddRange(stations); try { dbContext.SaveChanges(); } catch (Exception exception) { throw; } } }
private static void AddUserStateTest() { var user = new User { FirstName = "Marcin", LastName = $"N_{DateTime.Now.Hour}_{DateTime.Now.Minute}", Discount = 40, PhoneNumber = "123456789" }; using (var dbContext = new BikeRentalContext()) { try { // Add or update - own: // dbContext.Users.Any(u => u == user); // only bool // // performance best: Find(). dbContext.Entry(user); // State: Detached. dbContext.Users.Add(user); // Add user to context. dbContext.Entry(user); // State: Added. dbContext.SaveChanges(); // Save context changes. dbContext.Entry(user); // State: Unchanged. dbContext.Users.Remove(user); // Remove user. dbContext.Entry(user); // State: Deleted. dbContext.SaveChanges(); // Save context changes. dbContext.Entry(user); // State: Detached. } catch (Exception exception) { throw; } } }
public void StorageProceduresTest() { /* * * CREATE PROCEDURE uspDeleteBike(@BikeId int) * AS BEGIN * DELETE FROM [rentals].[Vehicles] WHERE [VehicleId] = @BikeId * END * */ Console.Write("Enter Bike ID to delete: "); var bikeId = Console.ReadLine(); var bikeIdParameter = new SqlParameter("@BikeId", bikeId); // Output parameter. // var outputParameter = new SqlParameter // { // Direction = System.Data.ParameterDirection.Output // }; using (var context = new BikeRentalContext()) { context.Database.ExecuteSqlCommand("uspDeleteBike @BikeId", bikeIdParameter); } }
private static void TryLoadingNonExistentBikeTest() { using (var context = new BikeRentalContext()) { var bike = context.Bikes.Find(15); // checking how non existent row will be retrieved // no exception } }
private static void UpdateUserViaSpTest() { using (var context = new BikeRentalContext()) { var user = context.Users.First(); user.FirstName = "Johnny"; context.SaveChanges(); } }
private static void SqlUpdateWithParamUnsafeTest(string color) { string sql = $"update[rentals].[Vehicles] set [IsActive] = 0 where [Color] = '{color}';"; using (var context = new BikeRentalContext()) { context.Database.ExecuteSqlCommand(sql); } }
private static void SqlUpdateTest() { string sql = "update[rentals].[Vehicles] set [IsActive] = 0;"; using (var context = new BikeRentalContext()) { context.Database.ExecuteSqlCommand(sql); } }
private static void DeserializeParametersTest() { using (var context = new BikeRentalContext()) { foreach (var station in context.Stations.Where(x => x.SerializedParameters != null)) { station.Parameters.Dump(); } } }
private static void SqlUpdateWithParamTest(string color) { string sql = $"update[rentals].[Vehicles] set [IsActive] = 0 where [Color] = @pColor;"; var colorParameter = new SqlParameter("pColor", color); using (var context = new BikeRentalContext()) { context.Database.ExecuteSqlCommand(sql, colorParameter); } }
private static void GetVehiclesTest() { using (var context = new BikeRentalContext()) { foreach (var v in context.Vehicles) { WriteLine($"{v.Number}, {v.GetType().FullName}"); } } }
private static void GetSqlTest() { string sql = $"SELECT * FROM [rentals].[Vehicles] where [Color] like 'r%' and Discriminator = 'Bike';"; using (var context = new BikeRentalContext()) { var bikes = context.Database.SqlQuery <Bike>(sql); bikes.ToList().Dump(); } }
private static void GetVehiclesTest() { using (var context = new BikeRentalContext()) { var vehicles = context.Vehicles; foreach (var vehicle in vehicles) { Console.WriteLine(vehicle.ToString()); } } }
private static void DeleteUserTest() { using (var context = new BikeRentalContext()) { var user = context.Users.Find(1); WriteLine(context.Entry(user).State); context.Users.Remove(user); WriteLine(context.Entry(user).State); context.SaveChanges(); } }
private static void SelectTest() { using (var context = new BikeRentalContext()) { var vehicles = context.Vehicles.Select(x => new { x.Color, x.Number }); foreach (var v in vehicles) { WriteLine(v); } WriteLine(vehicles.ToString()); } }
private static void UpdateParametersTest() { using (var context = new BikeRentalContext()) { var user = context.Users.Find(25); user.Parameters = new Parameters { P1 = DateTime.Now.Minute, P2 = DateTime.Now.Millisecond }; context.Entry(user).State = EntityState.Modified; // Property is ignored - force modification. context.SaveChanges(); } }
private static void GetRentalsNoLazyLoadingTest() { using (var context = new BikeRentalContext()) { var rentals = context.Rentals .ToList(); foreach (var r in rentals) { // Throws exception WriteLine($"{r.DateFrom} - {r.DateTo}: {r.User.LastName}"); } } }
private static void GetRentalsIncludeViaStringTest() { using (var context = new BikeRentalContext()) { var rentals = context.Rentals .Include("User") // Prone to typos and poor refactoring //.Include("User.Parameters") // In case of chained references .ToList(); foreach (var r in rentals) { WriteLine($"{r.DateFrom} - {r.DateTo}: {r.User.LastName}"); } } }
private static void SyntaxTest() { using (var context = new BikeRentalContext()) { var query = (from vehicle in context.Vehicles where vehicle.Color == "Red" orderby vehicle.Number select vehicle) .Where(x => x.Number.Contains("1")); WriteLine(query.ToString()); var unionDistinct = query.Distinct(); unionDistinct.ToList().Dump(); } }
private static void GetRentalsIncludeTest() { using (var context = new BikeRentalContext()) { var rentals = context.Rentals .Include(x => x.User) //.Include(x => x.User.Parameters) // In case of chained references .ToList(); foreach (var r in rentals) { WriteLine($"{r.DateFrom} - {r.DateTo}: {r.User.LastName}"); } } }
private static void UpdateBikeTest() { using (var context = new BikeRentalContext()) { var bike = context.Bikes.AsNoTracking().First(); bike.Color = "yellow!"; //context.Entry(bike).State = EntityState.Added; foreach (var e in context.ChangeTracker.Entries <Bike>()) { WriteLine(e.Entity); } context.SaveChanges(); } }
public void EagerLoadingTest() { using (var context = new BikeRentalContext()) { var rentals = context.Rentals .Include(r => r.User) // single // .Include("User.Parameters") // deeper, not recommended // .Include(r => r.User.Select) // deeper when list // .Include(r => r.User.Parameters) // deeper only for objects .ToList(); rentals.ForEach(r => Console.WriteLine($"{r.DateFrom} -> {r.User.FirstName} {r.User.LastName}") ); } }
private static void TransactionTest() { var badGuy = new Random(); using (var context = new BikeRentalContext()) using (var transaction = context.Database.BeginTransaction()) { try { // First action var user = new User { FirstName = "Jack", LastName = "Doe" }; context.Users.Add(user); context.SaveChanges(); if (badGuy.Next(2) == 0) { throw new Exception("Imma bad guy!"); } // Second action var bikeToRent = context.Bikes.First(); var station = context.Stations.First(); var promoRental = new Rental { StationFrom = station, Cost = 100, DateFrom = DateTime.Now, User = user, Vehicle = bikeToRent }; context.Rentals.Add(promoRental); context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); WriteLine(ex); } } }
private static void AddRental() { var userLukasz = new User { FirstName = "Lukasz", LastName = $"K_{DateTime.Now.Hour}_{DateTime.Now.Minute}", Discount = 60, PhoneNumber = "123123123" }; using (var dbContext = new BikeRentalContext()) { try { dbContext.Users.Add(userLukasz); dbContext.SaveChanges(); } catch (Exception exception) { throw; } } using (var dbContext = new BikeRentalContext()) { var user = dbContext.Users.First(u => u.FirstName.Contains("Luk")); var bike = dbContext.Vehicles.Find(1); var station = dbContext.Stations.Find(1); var rental = new Rental { Vehicle = bike, User = user, StationFrom = station, DateFrom = DateTime.Now }; try { dbContext.Rentals.Add(rental); dbContext.SaveChanges(); } catch (Exception exception) { throw; } } }