Imagine a little webshop which uses its own currency.

In the database, there is a table for items, which can be bought. The count of each item is limited. This limit is stored in a collumn in this table as integer.

Also, there is a table for the user's cash accounts, whereas for each account the current balance is saved.

If, for example, two users conduct their purchases at the same time and only one item is available, it could be possible that both users pay but only one receives the item due to racing conditions.

How can such racing conditions be resolved, without relying on entity framework throwing exceptions on saving?

How can I ensure the count of available items and the account balance of the buyer is correctly updated?

有帮助吗?

解决方案

This isn't really a problem specific to Entity Framework, it's applicable to just about any shop scenario. It comes down to a question of policy - the only way to ensure that two customers do not purchase the same item is to allow a temporary lock to be placed on that item when they add the item to the cart, or begin the checkout process, similar to how concert tickets or flights are sold. This lock would expire if the purchase is not completed within a set amount of time, and the item would be released back for other customers to purchase.

In an e-commerce setting, this is not as suitable, since people may add an item to their cart and not check out, or spend extra time choosing additional items. This may lead to the scenario where you have items for sale but they can't be bought because they're in someone's cart who's not planning on checking out. Instead, duplicate orders are allowed, but payments are typically only pre-authorised and then completed at the time of shipping or order confirmation, so even if the second customer enters all their details and presses Buy, their card wouldn't be charged since the item wouldn't be shippable.

You can implement checks at different stages during the Checkout process to ensure the items in the cart are still available, or at the simplest level, leave it for the final "Pay Now" button on the last page. Ultimately though, this just reduces the potential for the race condition, rather than eliminating it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top