Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using Casestudy.ViewModels;
- using Newtonsoft.Json;
- using Casestudy.Models;
- using System.Linq;
- namespace Casestudy.Models
- {
- public class OrderModel
- {
- private AppDbContext _db;
- public bool flag;
- public OrderModel(AppDbContext ctx)
- {
- _db = ctx;
- }
- public int AddOrder(Dictionary<string, object> items, string user)
- {
- int orderId = -1;
- using (_db)
- {
- // we need a transaction as multiple entities involved
- using (var _trans = _db.Database.BeginTransaction())
- {
- try
- {
- Order order = new Order();
- order.UserId = user;
- order.OrderDate = System.DateTime.Now;
- order.OrderAmount = 0.0M;
- // calculate the totals and then add the tray row to the table
- foreach (var key in items.Keys)
- {
- ProductViewModel item = JsonConvert.DeserializeObject<ProductViewModel>(Convert.ToString(items[key]));
- if (item.Qty > 0)
- {
- order.OrderAmount += item.MSRP * item.Qty * 1.13M;
- }
- }
- _db.Orders.Add(order);
- _db.SaveChanges();
- // then add each item to the orderproducts table
- foreach (var key in items.Keys)
- {
- ProductViewModel item = JsonConvert.DeserializeObject<ProductViewModel>(Convert.ToString(items[key]));
- if (item.Qty > 0)
- {
- OrderLineItem oli = new OrderLineItem();
- oli.Product = _db.Products.FirstOrDefault(p => p.Id == item.Id);
- oli.Order.Id = order.Id;
- if (oli.Product.QtyOnHand > item.Qty)
- {
- oli.Product.Id = item.Id;
- oli.Product.QtyOnHand -= item.Qty;
- oli.QtySold = item.Qty;
- oli.QtyOrdered = item.Qty;
- oli.QtyBackOrdered = 0;
- oli.SellingPrice = item.MSRP;
- }
- else
- {
- oli.QtyBackOrdered = item.Qty - oli.Product.QtyOnHand;
- oli.Product.QtyOnBackOrder += (item.Qty - oli.Product.QtyOnHand);
- oli.Product.QtyOnHand = 0;
- oli.QtyOrdered = item.Qty;
- oli.QtySold = oli.QtyOrdered - oli.QtyBackOrdered;
- oli.SellingPrice = item.MSRP;
- flag = true;
- }
- _db.OrderLineItems.Add(oli);
- _db.SaveChanges();
- }
- }
- // test trans by uncommenting out these 3 lines
- //int x = 1;
- //int y = 0;
- //x = x / y;
- _trans.Commit();
- orderId = order.Id;
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- _trans.Rollback();
- }
- }
- }
- return orderId;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement