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 IActionResult StartRental([FromQuery] int customerId, int bikeId) { Customer customer; Bike bike; Rental rental; try { customer = db.Customers.Where(p => p.ID == customerId).ToArray().Single(); bike = db.Bikes.Where(p => p.ID == bikeId).ToArray().Single(); List <Rental> rentals = db.Rentals.Where(p => p.Customer.ID == customerId && p.Bike.ID == bikeId).ToList(); foreach (Rental r in rentals) { if (r.RentalEnd == null) { return(BadRequest("Customer has an active Rental")); } } rental = new Rental { Customer = customer, Bike = bike, RentalBegin = DateTime.Now, Paid = false }; db.Rentals.Add(rental); db.SaveChanges(); } catch (Exception e) { return(BadRequest("Rental could not be startet")); } return(Ok(rental)); }
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 IActionResult CreateCustomers([FromBody] Customers cust) { if (cust == null) { return(BadRequest("Error")); } Context.Customers.Add(cust); Context.SaveChanges(); return(Ok("Customer created")); }
public IActionResult CreateBike([FromBody] Bikes bike) { if (bike == null) { return(BadRequest("Error")); } Context.Bikes.Add(bike); Context.SaveChanges(); return(Ok("Bike Created")); }
public IActionResult Post([FromBody] Customer customer) { if (ModelState.IsValid) { db.Customers.Add(customer); db.SaveChanges(); return(StatusCode(200, "Customer created.")); } else { return(StatusCode(400, "Customer could not be created.")); } }
public IActionResult Post([FromBody] Bike bike) { if (ModelState.IsValid) { db.Bikes.Add(bike); db.SaveChanges(); return(StatusCode(200, "Bike created.")); } else { return(StatusCode(400, "Bike could not be created.")); } }
public IActionResult Update(int bikeId, [FromBody] Bike bike) { Bike updateElement = dbContext.Bikes.Select(e => e).Where(e => e.BikeId == bikeId).FirstOrDefault(); updateElement.Brand = bike.Brand == null ? updateElement.Brand : bike.Brand; updateElement.Category = bike.Category == null ? updateElement.Category : dbContext.BikeCategorys.Where(c => c.CategoryId == bike.Category.CategoryId).FirstOrDefault(); updateElement.DateOfLastService = bike.DateOfLastService == null ? updateElement.DateOfLastService : bike.DateOfLastService; updateElement.Notes = bike.Notes == null ? updateElement.Notes : bike.Notes; updateElement.PurchaseDate = bike.PurchaseDate == null ? updateElement.PurchaseDate : bike.PurchaseDate; updateElement.RentalPriceExtraHour = bike.RentalPriceExtraHour == 0 ? updateElement.RentalPriceExtraHour : bike.RentalPriceExtraHour; updateElement.RentalPriceFirstHour = bike.RentalPriceFirstHour == 0 ? updateElement.RentalPriceFirstHour : bike.RentalPriceFirstHour; dbContext.SaveChanges(); return(StatusCode(200, updateElement)); }
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); } } }
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 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; } } }
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 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:"); } } }
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; } } }
public IActionResult Update(int custId, [FromBody] Customer cust) { // Getting the customer from the id Customer updateElement = dbContext.Customers.Select(e => e).Where(e => e.CustomerId == custId).FirstOrDefault(); // Checking which parameters are given in the Customer object from the body and porting them in the element updateElement.Birthday = cust.Birthday == null?updateElement.Birthday:cust.Birthday; updateElement.FirstName = cust.FirstName == null ? updateElement.FirstName : cust.FirstName; updateElement.LastName = cust.LastName == null ? updateElement.LastName : cust.LastName; updateElement.Gender = cust.Gender == null?updateElement.Gender:dbContext.PersonGenders.Where(e => e.GenderId == cust.Gender.GenderId).FirstOrDefault(); updateElement.HouseNumber = cust.HouseNumber == 0 ? updateElement.HouseNumber : cust.HouseNumber; updateElement.Street = cust.Street == null ? updateElement.Street : cust.Street; updateElement.Town = cust.Town == null ? updateElement.Town : cust.Town; updateElement.ZipCode = cust.ZipCode == 0 ? updateElement.ZipCode : cust.ZipCode; dbContext.SaveChanges(); return(StatusCode(200, updateElement)); }
private static void UpdateUserViaSpTest() { using (var context = new BikeRentalContext()) { var user = context.Users.First(); user.FirstName = "Johnny"; context.SaveChanges(); } }
public void SaveRental(Rental rental) { context.AttachRange(rental.Lines.Select(l => l.Bike)); if (rental.RentalId == 0) { context.Rentals.Add(rental); } context.SaveChanges(); }
public void SimpleTransaction() { using (var context = new BikeRentalContext()) using (var transaction = context.Database.BeginTransaction()) { try { // Modify 1 var user = context.Users.Find(1); user.PhoneNumber = DateTime.Now.ToString(); // Save 1 context.SaveChanges(); var bike = context.Vehicles.First(v => v.IsActive); var station = context.Stations.Find(1); var rental = new Rental { Cost = 10, DateFrom = DateTime.Now, StationFrom = station, User = user, Vehicle = bike, }; // Modify context.Rentals.Add(rental); // Rollback mock throw new Exception("Mock"); // Save 2 context.SaveChanges(); } catch (Exception exception) { transaction.Rollback(); throw; } transaction.Commit(); } }
private static void ExecuteSpWithOutParameterTest() { var proc = @" create procedure uspDeleteBikeWithColorOut(@BikeId int, @Color varchar(30) output) as begin select @Color = [color] from [rentals].[Vehicles] where [VehicleId] = @BikeId; delete from [rentals].[Vehicles] where [VehicleId] = @BikeId; end "; using (var context = new BikeRentalContext()) { context.Bikes.Add(new Bike { BikeType = BikeType.City, Color = "Blue!!!", Number = "B124" }); context.SaveChanges(); context.Bikes.ToList().Dump(); var bikeToDelete = context.Bikes.FirstOrDefault(x => x.Number == "B124"); if (bikeToDelete != null) { var idParameter = new SqlParameter("BikeId", bikeToDelete.VehicleId); var outputParameter = new SqlParameter { ParameterName = "Color", DbType = DbType.String, Size = 30, Direction = ParameterDirection.Output }; context.Database.ExecuteSqlCommand("uspDeleteBikeWithColorOut @BikeId, @Color OUTPUT", idParameter, outputParameter); context.SaveChanges(); outputParameter.Dump(); context.Bikes.ToList().Dump(); } } }
public IActionResult AddCustomer([FromBody] Customer customer) { try { if (ModelState.IsValid) { db.Customers.Add(customer); db.SaveChanges(); return(Ok("Customer added successfully")); } else { return(BadRequest("Error - Customer not created")); } } catch (Exception e) { return(BadRequest("Error - Customer not created")); } }
public IActionResult AddBike([FromBody] Bike bike) { try { if (ModelState.IsValid) { db.Bikes.Add(bike); db.SaveChanges(); return(Ok("Bike added successfully")); } else { return(BadRequest("Error - Bike not created")); } } catch (Exception e) { return(BadRequest("Error - Bike not created")); } }
public ActionResult DeleteBike(int bikeId) { var bikeToDelete = _context.Bikes.Find(bikeId); if (bikeToDelete == null) { return(BadRequest($"Bicycle with Id = {bikeId} can not be deleted, because it doesn't exist.")); } _context.Bikes.Remove(bikeToDelete); _context.SaveChanges(); return(NoContent()); }
public IActionResult Start([FromBody] Rental rent) { // Check if a importand parameter is missing if (rent.Buyer == null || rent.Buyer.CustomerId == 0 || rent.RentedBike == null || rent.RentedBike.BikeId == 0) { return(StatusCode(400, "Something is missing (Buyer or Bike?)")); } // Check if the Customer already has an open rental if (dbContext.Rentals.Where(r => r.Buyer.CustomerId == rent.Buyer.CustomerId && r.RentEndTime == null).ToArray().Length != 0) { return(StatusCode(400, "This Customer already has an active rental")); } // Set the Buyer and Bike as a Reference and reset other parameters rent.Buyer = dbContext.Customers.Where(c => c.CustomerId == rent.Buyer.CustomerId).FirstOrDefault(); if (rent.Buyer == null) { return(StatusCode(400, "Cant find Buyer")); } rent.RentedBike = dbContext.Bikes.Where(b => b.BikeId == rent.RentedBike.BikeId).FirstOrDefault(); if (rent.RentedBike == null) { return(StatusCode(400, "Cant find Bike")); } rent.RentEndTime = null; rent.RentStartTime = DateTime.Now; rent.TotalCost = 0; rent.PaidFlag = false; rent.RentalId = 0; // Add the rental to the databse dbContext.Rentals.Add(rent); dbContext.SaveChanges(); return(StatusCode(200, rent)); }
public IActionResult StartRental([FromQuery] int customerId, [FromQuery] int bikeId) { if (!db.Customers.Any(c => c.Id == customerId) || !db.Bikes.Any(b => b.Id == bikeId)) { return(StatusCode(404, "Couldn't create this rental. Please check the customerId and the bikeId you entered.")); } // Check if this customer already has an active rental if (db.Rentals.Any(r => r.Customer.Id == customerId && r.RentalBegin != null && r.RentalEnd == null)) { return(StatusCode(400, "This customer already has an active rental.")); } Rental rent = new Rental(); rent.Customer = db.Customers.FirstOrDefault(c => c.Id == customerId); if (rent.Customer == null) { return(StatusCode(404, "The customer could not be found.")); } rent.RentedBike = db.Bikes.FirstOrDefault(b => b.Id == bikeId); if (rent.RentedBike == null) { return(StatusCode(404, "The bike could not be found.")); } // Assign the values rent.RentalEnd = null; rent.RentalBegin = DateTime.Now; rent.TotalCosts = 0; rent.Paid = false; rent.Id = 0; db.Rentals.Add(rent); db.SaveChanges(); return(StatusCode(200, rent)); }
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 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(); } }
public ActionResult DeleteType(int Id) { var typeToDelete = _context.BikeTypes.Find(Id); if (typeToDelete == null) { return(BadRequest($"Bike Type with Id = {Id} not found. Can not delete.")); } _context.BikeTypes.Remove(typeToDelete); _context.SaveChanges(); return(Ok($"Bike type with Id= {Id} was deleted")); }
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(); } }