104 lines
3.3 KiB
C#
104 lines
3.3 KiB
C#
using CanteenContracts.BindingModels;
|
|
using CanteenContracts.View;
|
|
using CanteenDataModels.Enums;
|
|
using CanteenDataModels.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.ComponentModel.DataAnnotations.Schema;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace CanteenDatabaseImplement.Models
|
|
{
|
|
public class Order : IOrderModel
|
|
{
|
|
public int Id { get; private set; }
|
|
public int VisitorId { get; private set; }
|
|
public string Description { get; private set; } = string.Empty;
|
|
public double? Sum { get; private set; }
|
|
|
|
private Dictionary<int, (IDishModel, int)>? _orderDishes = null;
|
|
|
|
[NotMapped]
|
|
public Dictionary<int, (IDishModel, int)> OrderDishes
|
|
{
|
|
get
|
|
{
|
|
if (_orderDishes == null)
|
|
{
|
|
_orderDishes = Dishes
|
|
.ToDictionary(recOD => recOD.DishId, recOD => (recOD.Dish as IDishModel, recOD.Count));
|
|
}
|
|
return _orderDishes;
|
|
}
|
|
}
|
|
|
|
[ForeignKey("OrderId")]
|
|
public virtual List<OrderDish> Dishes { get; set; } = new();
|
|
|
|
public static Order Create(OrderBindingModel model)
|
|
{
|
|
if (model == null)
|
|
{
|
|
return null;
|
|
}
|
|
return new Order()
|
|
{
|
|
Id = model.Id,
|
|
VisitorId = model.VisitorId,
|
|
Description = model.Description,
|
|
Sum = model.Sum
|
|
};
|
|
}
|
|
|
|
public void Update(OrderBindingModel model)
|
|
{
|
|
if (model == null)
|
|
{
|
|
return;
|
|
}
|
|
VisitorId = model.VisitorId;
|
|
Description = model.Description;
|
|
Sum = model.Sum;
|
|
}
|
|
|
|
public OrderViewModel GetViewModel => new()
|
|
{
|
|
Id = Id,
|
|
VisitorId = VisitorId,
|
|
Description = Description,
|
|
Sum = Sum,
|
|
OrderDishes = OrderDishes
|
|
};
|
|
public void UpdateOrderDish(CanteenDatabase context, DishBindingModel model)
|
|
{
|
|
var orderDish = context.OrderDish.Where(rec => rec.DishId == model.Id).ToList();
|
|
if (orderDish != null && (orderDish.Count > 0))
|
|
{
|
|
context.OrderDish.RemoveRange(orderDish.Where(rec => !model.OrderDishes.ContainsKey(rec.DishesId)));
|
|
context.SaveChanges();
|
|
foreach (var updateDish in orderDish)
|
|
{
|
|
updateDish.CountProduct = model.OrderDishes[updateDish.DishesId].Item2;
|
|
model.OrderDishes.Remove(updateDish.DishesId);
|
|
}
|
|
context.SaveChanges();
|
|
}
|
|
var dish = context.Dishes.First(x => x.Id == Id);
|
|
foreach (var dp in model.OrderDishes)
|
|
{
|
|
context.OrderDish.Add(new DishProduct
|
|
{
|
|
Dish = dish,
|
|
Product = context.Products.First(x => x.Id == dp.Key),
|
|
CountProduct = dp.Value.Item2
|
|
});
|
|
context.SaveChanges();
|
|
}
|
|
_orderDishes = null;
|
|
}
|
|
}
|
|
}
|