views:

52

answers:

1

Hi,

In my program, there are two class, say, category and product, with each object of product hold a reference to the category it belongs to. When loading data from XML and store them in the database, a problem arise:

If I create a category object and store it in the database first, there will be dirty data when creating product failed.(I want each xml loading be transactional, thus if the user failed by some mistake, the database remains as before).

If I create product first, there will be no reference(CategoryID generated by database) for them. I also can validate all the products first, but there will be to much duplicated code in validation and object creation. What is the best practice?

Thanks in advance!

A: 

You should be using transactions in your database so that you can roll back the first insert if the second one fails.

In most databases, you can start a transaction with

START TRANSACTION

and if the whole thing goes fine, then you run

COMMIT

If something fails, your run

ROLLBACK

and all the data goes back to the point it was at before you started the transaction.

Kibbee
But, I'm doing this in a service layer, upon DAL, how can I provide the transaction to service layer then. Thanks!
Roy
What DAL technology are you using? In most cases, you can use transactions in your DAL (eg http://www.simple-talk.com/dotnet/.net-framework/.net-2.0-transaction-model/).
Nader Shirazie