2023-04-25 03:51:22 +04:00

109 lines
2.8 KiB
C#

using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string ShopName { get; set; } = string.Empty;
[Required]
public string Address { get; set; } = string.Empty;
[Required]
public DateTime DateOpen { get; set; }
[Required]
public int Capacity { get; set; }
private Dictionary<int, (IDocumentModel, int)>? _shopDocuments = null;
[NotMapped]
public Dictionary<int, (IDocumentModel, int)> ShopDocuments
{
get
{
if (_shopDocuments == null)
{
_shopDocuments = Documents
.ToDictionary(rec => rec.DocumentId,
rec => (rec.Document as IDocumentModel,
rec.Count));
}
return _shopDocuments;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopDocument> Documents { get; set; } = new();
public static Shop Create(LawFirmDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
Capacity = model.Capacity,
Documents = model.ShopDocuments.Select(x => new ShopDocument
{
Document = context.Documents.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel model)
{
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
Capacity = model.Capacity;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
Capacity = Capacity,
ShopDocuments = ShopDocuments
};
public void UpdateDocuments(LawFirmDatabase context, ShopBindingModel model)
{
var shopDocuments = context.ShopDocuments.Where(rec => rec.ShopId == model.Id).ToList();
if (shopDocuments != null && shopDocuments.Count > 0)
{
context.ShopDocuments.RemoveRange(shopDocuments.Where(rec => !model.ShopDocuments.ContainsKey(rec.DocumentId)));
context.SaveChanges();
foreach (var updateDocument in shopDocuments)
{
updateDocument.Count = model.ShopDocuments[updateDocument.DocumentId].Item2;
model.ShopDocuments.Remove(updateDocument.DocumentId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var id in model.ShopDocuments)
{
context.ShopDocuments.Add(new ShopDocument
{
Shop = shop,
Document = context.Documents.First(x => x.Id == id.Key),
Count = id.Value.Item2
});
context.SaveChanges();
}
_shopDocuments = null;
}
}
}