views:

132

answers:

2

The following simplified code doesn't work (because it sets the retrieved object reference to the parameter), but it shows what I want to do

 public bool updateEvent(clubEvent newEvent)
    {
        TNightCon tCon = new TNightCon();
        clubEvent cEv = (from cEvent in tCon.clubEvents
                         where cEvent.EventID == newEvent.EventID
                         select cEvent).First();

        // Won't work, but do I have to set all the fields manually?
        cEv = newEvent;
        tCon.SubmitChanges();
        return true;
    }
+2  A: 

Or, alternately,

  tCon.ClubEvents.DeleteOnSubmit(cEv);
  tCon.CLubEvents.InsertOnSubmit(newEvent);
  tCon.SubmitChanges();
James Curran
How safe is this though? Is there not a chance that between the deletion and the creation of the record that a query will try and find the record, but it won't exist? Or will SQL server complete these type of operations before it deals with new requests?
Tarks
James Curran
+1  A: 

You don't need to retrieve the current object to do what you need to do. If the Ids are the same, all you need to do is attach the new object to your context. The trick then becomes getting Linq2SQL to treat the object as "dirty". Timothy Khouri has a blog post that details a useful technique using the Refresh method on the context. Here's what it'd look like.

 public bool updateEvent(clubEvent newEvent)
    {
        tCon.clubEvents.Attach(newEvent);
        tCon.Refresh(RefreshMode.KeepCurrentValues, settings)
        tCon.SubmitChanges();
        return true;
    }
Jacob Proffitt