Updating a Single Column in Linq to SQL using Attach

This answer on Stack Overflow shows another way to update specific columns of a database record in Linq to SQL:

Call the table’s Attach() method passing the new values and a dummy set of old values.

In the .dbml file, the table’s columns (except for the primary key column(s)) need to have their UpdateCheck property set to Never (default is Always).

To update only specific columns, you need to instantiate two table objects: one containing the new values to be set, and one containing values different from the values to be set. The different values need not be the actual values of the record:

using (var database = new DataContext())
{
  database.FooMaxNevers.Attach(
    new FooMaxNever() { OID = OID, ID = newID }, 
    new FooMaxNever() { OID = OID, ID = "some random value" });
  database.SubmitChanges();
}

This code generates the following SQL statement

UPDATE [dbo].[FooMax]
SET   [ID]  = @p1
WHERE [OID] = @p0

Note that this method does not retrieve the current values and instantiate an object based on the actual database record, and therefore does not generate a SELECT statement.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.