开发者

ASP.NET calculated properties on object, should be in db or calculated runtime?

开发者 https://www.devze.com 2023-01-05 21:32 出处:网络
I have a small webshop-like web application, and i have big plans :-) I have a basket object and a basketitem object, the basket has a list of basketitems. At runtime i dont have the list, it has to b

I have a small webshop-like web application, and i have big plans :-) I have a basket object and a basketitem object, the basket has a list of basketitems. At runtime i dont have the list, it has to be loaded from database (using a repository pattern) with the id of the basket. The basket can exist for several days (max 30 days) and the customer can add basketItems to the basket during this interval开发者_开发问答.

What is the best approach to calculating the total (i have several similar calculations to make) of the basket, should i maintain a field in the database and update it when i add something to the basket or should i calculate it on the fly as a property (for databinding purposes)?

Lets say I have to make two calculations on this basket, one for the total, and one with a discount (tricky algorithm, dependent on many variables).

How about 3, 4 or 5 calculations, which is the best approach?


I would calculate the total on the fly - if the price of any of the individual items change whilst they are in a customer basket, then I would imagine that you would want to sell them at the new price if the prices have gone up or would want to pass any savings on to the customer if they have gone down :)

If you're storing it in a database, it's redundant data - you have all of the data that you need to calculate it already stored against the individual items. It also means that you would need to update that database table/field each time the user logs in to update the total.


This should not be stored in the database since the purchase hasnt been completed yet. Any product within the basket may have changed price during the time when the item was added, and you calculate the total amount.

Same goes for discounts, some are time limited and need to be reevaluated.


Such calculations, especially if they are subject to frequent changes are best calculated on the fly.

Otherwise, you will end up with having to update these database fields for all existing baskets, over and over again.


I would use a combined approach, calculating prices on the fly for items in the shopping basket, then storing all calculated values later on, when the items have been paid for. This way I'd have the benefit of allowing price changes and discounts for products while skipping the calculations when a client visits her previous orders.

0

精彩评论

暂无评论...
验证码 换一张
取 消