From ce944a6803102092d654ea44d53e6f3a4318e8b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D1=8F=D1=80=20=D0=90=D0=B3=D0=BB?= =?UTF-8?q?=D0=B8=D1=83=D0=BB=D0=BB=D0=BE=D0=B2?= Date: Wed, 1 Mar 2023 02:38:30 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=D0=B0=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BA=D0=B0?= =?UTF-8?q?=20=D0=BF=D1=80=D0=BE=D0=B4=D0=B0=D0=B6=D0=B8=20=D0=B8=D0=B7?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ConfectioneryDatabaseImplement/ShopStorage.cs | 41 ++++++++++--------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/ConfectioneryDatabaseImplement/ShopStorage.cs b/ConfectioneryDatabaseImplement/ShopStorage.cs index d541ceb..133c0e4 100644 --- a/ConfectioneryDatabaseImplement/ShopStorage.cs +++ b/ConfectioneryDatabaseImplement/ShopStorage.cs @@ -107,34 +107,37 @@ namespace ConfectioneryDatabaseImplement public bool HasNeedPastries(IPastryModel pastry, int needCount) { - using var context = new ConfectioneryDatabase(); - var resultCount = context.Shops - .Select(shop => shop.Pastries - .FirstOrDefault(x => x.Key == pastry.Id).Value.Item2) - .Sum(); - return resultCount >= needCount; + throw new NotImplementedException(); } public bool SellPastries(IPastryModel pastry, int needCount) { - if (!HasNeedPastries(pastry, needCount)) - { - return false; - } using var context = new ConfectioneryDatabase(); - foreach (var shop in context.Shops.Where(shop => shop.Pastries.ContainsKey(pastry.Id))) + using var transaction = context.Database.BeginTransaction(); + foreach (var sp in context.ShopPastries.Where(x => x.PastryId == pastry.Id)) { - var tuple = shop.Pastries[pastry.Id]; - var diff = Math.Min(tuple.Item2, needCount); - shop.Pastries[pastry.Id] = (tuple.Item1, tuple.Item2 - diff); - - needCount -= diff; - if (needCount <= 0) + var res = Math.Min(needCount, sp.Count); + sp.Count -= res; + needCount -= res; + if (sp.Count == 0) // Изделия больше нет в магазине, значит удаляем его { - return true; + context.ShopPastries.Remove(sp); + } + if (needCount == 0) // Нельзя коммитить изменения в цикле, что использует контекст, поэтому выходим + { + break; } } - return true; + if (needCount == 0) + { + context.SaveChanges(); + transaction.Commit(); + } + else + { + transaction.Rollback(); + } + return needCount == 0; } } }