public async Task <Purchase> PurchaseProduct(string userId, int productId, int quantity) { using (var tx = await db.Database.BeginTransactionAsync()) { if (quantity < 1) { throw new ArgumentException("Quantity must be greater or equal to 1", nameof(quantity)); } ; var product = await db.Products.FindAsync(productId); if (product == null) { throw new ArgumentException($"Unknown product: {productId}", nameof(productId)); } if (product.IsDeleted) { throw new InvalidOperationException($"Product {productId} is deleted"); } var user = await db.Users.FindAsync(userId); if (user == null) { throw new ArgumentException($"Unknown user: {userId}", nameof(userId)); } if (user.IsDeleted) { throw new InvalidOperationException($"User {userId} is deleted"); } var purchase = new Purchase { Product = product, Quantity = quantity, ProductPrice = product.Price, ProductName = product.Name, Amount = quantity * product.Price }; RecordTransaction(purchase, user); await db.SaveChangesAsync(); tx.Commit(); return(purchase); } }
private async Task Run(SubscriptionFrequency frequency) { using (var tx = await db.Database.BeginTransactionAsync()) { var subscriptions = await GetSubscriptions(frequency); foreach (var subscription in subscriptions) { Process(subscription); } await db.SaveChangesAsync(); tx.Commit(); } }