95 lines
3.3 KiB
C#
95 lines
3.3 KiB
C#
using SushiBarContracts.BindingModels;
|
|
using SushiBarContracts.ViewModels;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.ComponentModel.DataAnnotations.Schema;
|
|
|
|
namespace SushiBarDatabaseImplement.Models
|
|
{
|
|
public class Dish
|
|
{
|
|
[Key]
|
|
public int Id { get; set; }
|
|
|
|
[Required]
|
|
public string DishName { get; set; } = string.Empty;
|
|
|
|
[Required]
|
|
public string Category { get; set; } = string.Empty;
|
|
|
|
[ForeignKey("DishId")]
|
|
public virtual List<DishIngredient> DishIngredients { get; set; } = new();
|
|
|
|
[ForeignKey("DishId")]
|
|
public virtual List<ChequeItem> ChequeItems { get; set; } = new();
|
|
|
|
public static Dish Create(SushiBarDatabase Context, DishBindingModel Model)
|
|
{
|
|
return new Dish()
|
|
{
|
|
DishName = Model.DishName,
|
|
Category = Model.Category,
|
|
DishIngredients = Model.Ingredients.Select(x => new DishIngredient
|
|
{
|
|
Ingredient = Context.Ingredients.First(y => y.Id == x.IngredientId),
|
|
Count = x.Count,
|
|
}).ToList()
|
|
};
|
|
}
|
|
|
|
public void Update(DishBindingModel Model)
|
|
{
|
|
DishName = Model.DishName;
|
|
Category = Model.Category;
|
|
}
|
|
|
|
public DishViewModel ViewModel => new()
|
|
{
|
|
Id = Id,
|
|
DishName = DishName,
|
|
Category = Category,
|
|
Ingredients = DishIngredients.ToDictionary(x => x.IngredientId, x => new DishIngredientViewModel
|
|
{
|
|
DishId = x.DishId,
|
|
IngredientId = x.IngredientId,
|
|
IngredientName = x.Ingredient.IngredientName,
|
|
Count = x.Count,
|
|
})
|
|
};
|
|
|
|
public void UpdateIngredients(SushiBarDatabase Context, DishBindingModel Model)
|
|
{
|
|
var IngredientsForThisDish = Context.DishIngredients.Where(x => x.DishId == Model.Id).ToList();
|
|
|
|
if (IngredientsForThisDish.Count > 0)
|
|
{
|
|
// Delete DishIngredient records for selected dish if there is no record with such ingredient in passed model
|
|
var UsedComponentIds = Model.Ingredients.Select(x => x.IngredientId).ToList();
|
|
Context.DishIngredients.RemoveRange(IngredientsForThisDish.Where(x => !UsedComponentIds.Contains(x.IngredientId)));
|
|
Context.SaveChanges();
|
|
|
|
foreach (var DishIngredientToUpdate in IngredientsForThisDish)
|
|
{
|
|
DishIngredientToUpdate.Count = Model.Ingredients.First(x => x.IngredientId == DishIngredientToUpdate.IngredientId).Count;
|
|
Model.Ingredients.Remove(Model.Ingredients.First(x => x.IngredientId == DishIngredientToUpdate.IngredientId));
|
|
}
|
|
|
|
Context.SaveChanges();
|
|
}
|
|
|
|
var Dish = Context.Dishes.First(x => x.Id == Id);
|
|
|
|
foreach (var DishIngredient in Model.Ingredients)
|
|
{
|
|
Context.DishIngredients.Add(new DishIngredient
|
|
{
|
|
Dish = Dish,
|
|
Ingredient = Context.Ingredients.First(x => x.Id == DishIngredient.IngredientId),
|
|
Count = DishIngredient.Count
|
|
});
|
|
|
|
Context.SaveChanges();
|
|
}
|
|
}
|
|
}
|
|
}
|