views:

85

answers:

2

I have a linq object that I'd like to "retire" when certain aspects are changed and the Save() method is called. The database does this by having a Terminated column which when set causes the object to be ignored on subsequent queries. I'd like to do this transparently so for example:

DataContext db = new DataContext();
Foo bar = (from a in db.table
           where a.pk == somevalue
           select a).Single();

bar.Price += 2;
Console.WriteLine(bar.pk);
bar.Save();
Console.WriteLine(bar.pk);

The second WriteLine() should be a different key than the first because in the process of saving I've created a duplicate object and replaced bar with it. Essentially inside the save method I want to set this = newObj;. Is what I want possible or am I going about this the wrong way?

+1  A: 

You can change references (or more precisely the variables that hold them) if they are passed by reference:

class Foo {
  ...
  public static void Save(ref Foo obj)
  {
    var newObj = obj._save() //your implementation
    obj = newObj;
  }
}

There is no other way to change references. The reason is, that objects don't know where they are referenced. The Foo object doesn't know about any references to it.

If you want the exact behaviour you outlined in your code, the only way to achieve this, is to change the contents of your Foo instance, i.e., overwrite each and every field with the updated values.

Hope this helps.

SealedSun
A: 

An alternative would be to return the new object from the Save() method; This probably makes more sense if the Save() method is not part of the object. So for example:

var dataPersister = new DataPersister();
var obj = dataPersister.Load(somevalue);
obj.Price += 2;
var newObj = dataPersister.Save(obj);

After those calls, obj would still point at the original object, newObj would be the result after saving.

Chris Shaffer