ISEbd-21_Khaliullov_R.A._Co.../Canteen/CanteenDatabaseImplement/Models/Dish.cs
Руслан Халиуллов 0cf8214b3e 2 этап
2024-04-30 18:48:42 +04:00

97 lines
2.8 KiB
C#

using CanteenDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
using CanteenContracts.BindingModels;
using CanteenContracts.ViewModels;
namespace CanteenDatabaseImplement.Models
{
public class Dish : IDishModel
{
public int Id { get; set; }
[Required]
public string DishName { get; set; } = string.Empty;
[Required]
public double DishPrice { get; set; }
private Dictionary<int, (IIngredientModel, int)>? _DishIngredients = null;
[NotMapped]
public Dictionary<int, (IIngredientModel, int)> DishIngredients
{
get
{
if (_DishIngredients == null)
{
_DishIngredients = Ingredients
.ToDictionary(recPC => recPC.IngredientId, recPC =>
(recPC.Ingredient as IIngredientModel, recPC.Count));
}
return _DishIngredients;
}
}
[ForeignKey("DishId")]
public virtual List<DishIngredient> Ingredients { get; set; } = new();
[ForeignKey("DishId")]
public virtual List<Order> Orders { get; set; } = new();
public static Dish Create(CanteenDatabase context, DishBindingModel model)
{
return new Dish()
{
Id = model.Id,
DishName = model.DishName,
DishPrice = model.DishPrice,
Ingredients = model.DishIngredients.Select(x => new DishIngredient
{
Ingredient = context.Ingredients.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(DishBindingModel model)
{
DishName = model.DishName;
DishPrice = model.DishPrice;
}
public DishViewModel GetViewModel => new()
{
Id = Id,
DishName = DishName,
DishPrice = DishPrice,
DishIngredients = DishIngredients
};
public void UpdateMaterials(CanteenDatabase context, DishBindingModel model)
{
var DishIngredients = context.DishIngredients.Where(rec => rec.DishId == model.Id).ToList();
if (DishIngredients != null && DishIngredients.Count > 0)
{
context.DishIngredients.RemoveRange(DishIngredients.Where(rec => !model.DishIngredients.ContainsKey(rec.IngredientId)));
context.SaveChanges();
foreach (var updateIngredient in DishIngredients)
{
updateIngredient.Count = model.DishIngredients[updateIngredient.IngredientId].Item2;
model.DishIngredients.Remove(updateIngredient.IngredientId);
}
context.SaveChanges();
}
var Dish = context.Dishes.First(x => x.Id == Id);
foreach (var pc in model.DishIngredients)
{
context.DishIngredients.Add(new DishIngredient
{
Dish = Dish,
Ingredient = context.Ingredients.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_DishIngredients = null;
}
}
}