tags:

views:

19

answers:

1

Let's say I have a database that stores Fruit and FruitBaskets, and it's already populated with plenty of each. In my code I'm using Linq-to-Sql so that I can treat the rows of the database as instances of the OO classes Fruit and FruitBasket. Let's say that I want to create a temporary FruitBasket in code, process with it, but I do not want the FruitBasket to be persisted to the database. How do I achieve this using Linq-to-Sql?

The default I've found in Linq-to-Sql is that if I create a new, empty FruitBasket and add a Fruit to it that I had retrieved from the database, then the new FruitBasket will be automatically inserted to the data base upon my call to dataContext.SubmitChanges() (whether or not I have called insertUponSubmit()). Usually this is the right thing , but sometimes I want to be able to create a new FruitBasket without having it automatically inserted into the DB. Ideas? Best practices?

+1  A: 

If you set DataContext.ObjectTrackingEnabled = false; then it shout prevent this. You need to make sure you set it before querying the data context.

Ben Robinson
Ok... that sounds hopeful, but I need more details. Let's say I get a bunch of `Fruit` from the db and I want to make a temporary `FruitBasket`. Can I now turn off the object tracking, or is it already too late for that?
John Berryman
Yes it is already too late for that, if you try to set the property after you have retreived the fruit it will throw an exception. You need to set it before you retreive any data from the data context. Hmm reading the info further, you also cannot call SubmitChanges if it is set to false so it might not be of use to you.
Ben Robinson
Well, it at least looks like a good starting point. Thanks!
John Berryman