PIbd-21_BatylkinaAO_MusoevD.../Canteen/CanteenDatabaseImplement/Models/Lunch.cs
2023-04-07 17:58:07 +03:00

90 lines
3.0 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.Text;
using System.Threading.Tasks;
using CanteenContracts.BindingModels;
using CanteenContracts.View;
namespace CanteenDatabaseImplement.Models
{
public class Lunch : ILunchModel
{
public int Id { get; private set; }
public int VisitorId { get; private set; }
public string LunchName { get; private set; } = string.Empty;
public double Cost { get; private set; }
private Dictionary<int, (IProductModel, int)>? _lunchProducts = null;
public Dictionary<int, (IProductModel, int)> LunchProducts
{
get
{
if (_lunchProducts == null)
{
_lunchProducts = Products
.ToDictionary(recPC => recPC.ProductId, recPC => (recPC.Product as IProductModel, recPC.CountProduct));
}
return _lunchProducts;
}
}
[ForeignKey("LunchId")]
public virtual List<OrderLunch> Orders { get; set; } = new();
public virtual List<LunchProduct> Products { get; set; } = new();
public static Lunch? Create(CanteenDatabase context, LunchBindingModel model)
{
return new Lunch()
{
Id = model.Id,
VisitorId = model.VisitorId,
LunchName = model.LunchName,
Cost = model.Cost,
Products = model.LunchProducts.Select(x => new LunchProduct
{
Product = context.Products.First(y => y.Id == x.Key)
}).ToList()
};
}
public void Update(LunchBindingModel model)
{
LunchName = model.LunchName;
Cost = model.Cost;
}
public LunchViewModel GetViewModel => new()
{
Id = Id,
VisitorId = VisitorId,
LunchName = LunchName,
Cost = Cost,
LunchProducts = LunchProducts
};
public void UpdateProduct(CanteenDatabase context, LunchBindingModel model)
{
var lunchProducts = context.LunchProducts.Where(record => record.ProductId == model.Id).ToList();
if (lunchProducts != null && lunchProducts.Count > 0)
{
context.LunchProducts.RemoveRange(lunchProducts.Where(record => !model.LunchProducts.ContainsKey(record.ProductId)));
context.SaveChanges();
}
var product = context.Products.First(x => x.Id == Id);
foreach (var pc in model.LunchProducts)
{
context.LunchProducts.Add(new LunchProduct
{
Product = product,
Lunch = context.Lunches.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_lunchProducts = null;
}
}
}