PIbd-21_BatylkinaAO_MusoevD.../Canteen/CanteenDatabaseImplement/Models/Order.cs

104 lines
3.3 KiB
C#
Raw Normal View History

2023-04-07 23:35:33 +04:00
using CanteenContracts.BindingModels;
using CanteenContracts.View;
using CanteenDataModels.Enums;
2023-04-07 10:55:40 +04:00
using CanteenDataModels.Models;
using System;
using System.Collections.Generic;
2023-04-07 18:58:07 +04:00
using System.ComponentModel.DataAnnotations;
2023-04-07 10:55:40 +04:00
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenDatabaseImplement.Models
{
public class Order : IOrderModel
{
2023-04-07 18:58:07 +04:00
public int Id { get; private set; }
public int VisitorId { get; private set; }
public string Description { get; private set; } = string.Empty;
2023-04-07 23:35:33 +04:00
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;
}
}
2023-04-07 10:55:40 +04:00
[ForeignKey("OrderId")]
2023-04-07 23:35:33 +04:00
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;
}
2023-04-07 10:55:40 +04:00
}
}