Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.98 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using Casestudy.ViewModels;
  4. using Newtonsoft.Json;
  5. using Casestudy.Models;
  6. using System.Linq;
  7.  
  8. namespace Casestudy.Models
  9. {
  10. public class OrderModel
  11. {
  12. private AppDbContext _db;
  13. public bool flag;
  14. public OrderModel(AppDbContext ctx)
  15. {
  16. _db = ctx;
  17. }
  18. public int AddOrder(Dictionary<string, object> items, string user)
  19. {
  20. int orderId = -1;
  21. using (_db)
  22. {
  23. // we need a transaction as multiple entities involved
  24. using (var _trans = _db.Database.BeginTransaction())
  25. {
  26. try
  27. {
  28. Order order = new Order();
  29. order.UserId = user;
  30. order.OrderDate = System.DateTime.Now;
  31. order.OrderAmount = 0.0M;
  32. // calculate the totals and then add the tray row to the table
  33. foreach (var key in items.Keys)
  34. {
  35. ProductViewModel item = JsonConvert.DeserializeObject<ProductViewModel>(Convert.ToString(items[key]));
  36. if (item.Qty > 0)
  37. {
  38. order.OrderAmount += item.MSRP * item.Qty * 1.13M;
  39. }
  40. }
  41. _db.Orders.Add(order);
  42. _db.SaveChanges();
  43. // then add each item to the orderproducts table
  44. foreach (var key in items.Keys)
  45. {
  46. ProductViewModel item = JsonConvert.DeserializeObject<ProductViewModel>(Convert.ToString(items[key]));
  47. if (item.Qty > 0)
  48. {
  49. OrderLineItem oli = new OrderLineItem();
  50. oli.Product = _db.Products.FirstOrDefault(p => p.Id == item.Id);
  51. oli.Order.Id = order.Id;
  52. if (oli.Product.QtyOnHand > item.Qty)
  53. {
  54. oli.Product.Id = item.Id;
  55. oli.Product.QtyOnHand -= item.Qty;
  56. oli.QtySold = item.Qty;
  57. oli.QtyOrdered = item.Qty;
  58. oli.QtyBackOrdered = 0;
  59. oli.SellingPrice = item.MSRP;
  60. }
  61. else
  62. {
  63. oli.QtyBackOrdered = item.Qty - oli.Product.QtyOnHand;
  64. oli.Product.QtyOnBackOrder += (item.Qty - oli.Product.QtyOnHand);
  65. oli.Product.QtyOnHand = 0;
  66. oli.QtyOrdered = item.Qty;
  67. oli.QtySold = oli.QtyOrdered - oli.QtyBackOrdered;
  68. oli.SellingPrice = item.MSRP;
  69. flag = true;
  70. }
  71. _db.OrderLineItems.Add(oli);
  72. _db.SaveChanges();
  73.  
  74. }
  75. }
  76. // test trans by uncommenting out these 3 lines
  77. //int x = 1;
  78. //int y = 0;
  79. //x = x / y;
  80. _trans.Commit();
  81. orderId = order.Id;
  82. }
  83. catch (Exception ex)
  84. {
  85. Console.WriteLine(ex.Message);
  86. _trans.Rollback();
  87. }
  88. }
  89. }
  90. return orderId;
  91. }
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement