PIbd-23_Nevaeva_K.A._Travel.../TravelCompany/TravelCompanyDatabaseImplement/Models/Travel.cs

100 lines
3.7 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TravelCompanyDatabaseImplement.Models
{
public class Travel : ITravelModel
{
public int Id { get; set; }
[Required]
public string TravelName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IConditionModel, int)>? _travelConditions = null;
[NotMapped]
public virtual List<Order> Orders { get; set; } = new();
public Dictionary<int, (IConditionModel, int)> TravelConditions
{
get
{
if (_travelConditions == null)
{
_travelConditions = Conditions.ToDictionary(recPC => recPC.ConditionId, recPC =>
(recPC.Condition as IConditionModel, recPC.Count));
}
return _travelConditions;
}
}
[ForeignKey("TravelId")]
public virtual List<TravelCondition> Conditions { get; set; } = new();
public static Travel Create(TravelCompanyDatabase context,
TravelBindingModel model)
{
return new Travel()
{
Id = model.Id,
TravelName = model.TravelName,
Price = model.Price,
Conditions = model.TravelConditions.Select(x => new
TravelCondition
{
Condition = context.Conditions.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(TravelBindingModel model)
{
TravelName = model.TravelName;
Price = model.Price;
}
public TravelViewModel GetViewModel => new()
{
Id = Id,
TravelName = TravelName,
Price = Price,
TravelConditions = TravelConditions
};
public void UpdateConditions(TravelCompanyDatabase context,
TravelBindingModel model)
{
var travelConditions = context.TravelConditions.Where(rec => rec.TravelId == model.Id).ToList();
if (travelConditions != null && travelConditions.Count > 0)
{ // удалили те, которых нет в модели
context.TravelConditions.RemoveRange(travelConditions.Where(rec
=> !model.TravelConditions.ContainsKey(rec.ConditionId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateCondition in travelConditions)
{
updateCondition.Count =
model.TravelConditions[updateCondition.ConditionId].Item2;
model.TravelConditions.Remove(updateCondition.ConditionId);
}
context.SaveChanges();
}
var travel = context.Travels.First(x => x.Id == Id);
foreach (var pc in model.TravelConditions)
{
context.TravelConditions.Add(new TravelCondition
{
Travel = travel,
Condition = context.Conditions.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_travelConditions = null;
}
}
}