Skip to content

Commit

Permalink
Reverting #20 - there were issues with 3 or more items in cart.
Browse files Browse the repository at this point in the history
  • Loading branch information
ma-rybak committed Nov 18, 2020
1 parent 3dcf91d commit 899be21
Showing 1 changed file with 56 additions and 3 deletions.
59 changes: 56 additions & 3 deletions WebGoatCore/Data/OrderRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,63 @@ public Order GetOrderById(int orderId)
}

public int CreateOrder(Order order)
{
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
_context.ChangeTracker.TrackGraph(order, node => node.Entry.State = !node.Entry.IsKeySet ? EntityState.Added : EntityState.Unchanged);
_context.SaveChanges();
// These commented lines cause EF Core to do wierd things.
// Instead, make the query manually.

// order = _context.Orders.Add(order).Entity;
// _context.SaveChanges();
// return order.OrderId;

string shippedDate = order.ShippedDate.HasValue ? "'" + string.Format("yyyy-MM-dd", order.ShippedDate.Value) + "'" : "NULL";
var sql = "INSERT INTO Orders (" +
"CustomerId, EmployeeId, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, " +
"ShipCity, ShipRegion, ShipPostalCode, ShipCountry" +
") VALUES (" +
$"'{order.CustomerId}','{order.EmployeeId}','{order.OrderDate:yyyy-MM-dd}','{order.RequiredDate:yyyy-MM-dd}'," +
$"{shippedDate},'{order.ShipVia}','{order.Freight}','{order.ShipName}','{order.ShipAddress}'," +
$"'{order.ShipCity}','{order.ShipRegion}','{order.ShipPostalCode}','{order.ShipCountry}')";
sql += ";\nSELECT OrderID FROM Orders ORDER BY OrderID DESC LIMIT 1;";

using (var command = _context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = sql;
_context.Database.OpenConnection();

using var dataReader = command.ExecuteReader();
dataReader.Read();
order.OrderId = Convert.ToInt32(dataReader[0]);
}

sql = ";\nINSERT INTO OrderDetails (" +
"OrderId, ProductId, UnitPrice, Quantity, Discount" +
") VALUES ";
foreach (var (orderDetails, i) in order.OrderDetails.WithIndex())
{
orderDetails.OrderId = order.OrderId;
sql += (i > 0 ? "," : "") +
$"('{orderDetails.OrderId}','{orderDetails.ProductId}','{orderDetails.UnitPrice}','{orderDetails.Quantity}'," +
$"'{orderDetails.Discount}')";
}

if (order.Shipment != null)
{
var shipment = order.Shipment;
shipment.OrderId = order.OrderId;
sql += ";\nINSERT INTO Shipments (" +
"OrderId, ShipperId, ShipmentDate, TrackingNumber" +
") VALUES (" +
$"'{shipment.OrderId}','{shipment.ShipperId}','{shipment.ShipmentDate:yyyy-MM-dd}','{shipment.TrackingNumber}')";
}

using (var command = _context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = sql;
_context.Database.OpenConnection();
command.ExecuteNonQuery();
}

return order.OrderId;
}

Expand Down

0 comments on commit 899be21

Please sign in to comment.