private decimal TryAssignPurchase(IDemandToProvider demand, decimal amount) { var purchaseParts = _context.PurchaseParts.Where(a => a.State != State.Finished && a.ArticleId == demand.ArticleId).ToList(); var amountAlreadyReserved = purchaseParts.Select(a => a.DemandProviderPurchaseParts.Sum(b => b.Quantity)).Sum(); var amountReservable = purchaseParts.Select(a => a.Quantity).Sum() - amountAlreadyReserved; if (amountReservable == 0) { return(amount); } var amountReserving = amountReservable > amount ? amount : amountReservable; _context.CreateDemandProviderStock(demand, amountReserving); amount -= amountReserving; return(amount); }