views:

77

answers:

2

I have a single linq to sql class. I would like to detect if it is new (meaning an insert will be done) or if there are any pending changes (update will be done). I realize that I can do this by using a partial class and hooking into the on change events for each property. However that is a lot of maintenance for a class that is constantly changing.

Is there a better way?

+3  A: 

You can check through the DataContext class.

First, check the ObjectTrackingEnabled property on the DataContext. If it returns false, then the object is not being tracked by the context.

Then, call the GetChangeSet method on the DataContext. From there, compare the references exposed by the Deletes, Updates, and Inserts properties against your object.

If the reference is found in any of those lists, then your object is being tracked by that list and you can proceed from there.

casperOne
So the only way to do it is from the DataContext then? I was hoping to just do it from the object instance alone.
Jason Webb
@Jason Webb: If you don't have a DataContext then it's irrelevant, you can't do an insert, update, or delete without one, and the state of the object is detached.
casperOne
A: 

Check if the id of the object is 0.

if someId = 0
  Insert();
else
  Update();

Simples

vikp
Research DeferredLoading and google for Detach() method - it's something you'll have to implement, but it'll save you some trouble with inserting through LINQ.
vikp