views:

46

answers:

2

Can we update a record using Table.Attach() in LINQ to SQL?

If yes, how?

The idea is, I shall create a new object, attach it to the Table (which in turn will be attached to DataContext), then I shall submit changes, etc. It ID matches, the existing object will be updated.

A: 

You would have to do the following:

  1. De-Serialize the object from its source. (Table.Attach() should only be used to re-associate an entity to a DataContext after it has been serialized).

  2. Call Table.Attach() to attach the entity to the table.

  3. Make your updates to the entity.

  4. Call DbContext.SubmitChanges();

Justin Niessner
But I was talking about creating a new object and then attach it.
JMSA
Then Table.Attach() is the wrong way to do things. You need to create a new instance of your object and then call Table.InsertOnSubmit().
Justin Niessner
A: 

If you use the RowVersion column, Attach() can be used. In different case you will need to pass both modified and original objects to the Attach method parameters. More information is available here.

Devart