Thursday, December 27, 2007

Linq To Sql, Attach, Using a DateTime as Timestamp and large bottle of ibuprofren!!!


You use LINQ to SQL (L2S) as your ORM, you create a business layer that supplies a list of customer entities to the presentation layer. The UI presents the data in a gridview where the user can update the info.

When the user clicks update, it passes a new instance of the entity to your BL method. Now you might be tempted to think that you simply use the Attach method of the Customers table and everythings fine and dandy. Oh that it were true. Be ready for:

"System.InvalidOperationException: An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy."

The entity being passed to your BL here is *not* the same one that went out. It is a new one created by the GridView as part of the update. Thus, it has no idea of the original context and your new context has no idea of it's original state.

If you have add a timestamp column that can be used by L2S to determine if the row has changed, you can make things work fine. This has some advantages in that it reduces the amount of T-Sql generated to perform the update.

// Business Layer code to get the list and perform the update.
public static List ListCustomers()
    using (SandboxDataContext dataContext = new SandboxDataContext())
        var custs = from c in dataContext.Customers orderby c.CustomerName select c ;
        return custs.ToList();

public static void UpdateCustomer(Customer c)
    using (SandboxDataContext dataContext = new SandboxDataContext())
        dataContext.Customers.Attach(c, true);

Note: You must use the Attach(entity, true) overload to actually save the changes.
Note: Make sure you configure the DataKeys property of your grid to include the primary key and the timestamp. Otherwise, you get a ChangeConflictException -- Row not found or changed.

-- T-Sql generated by L2S

exec sp_executesql N'UPDATE [dbo].[Customers]
SET [CustomerName] = @p2
WHERE ([CustomerKey] = @p0) AND ([TimeStamp] = @p1)

SELECT [t1].[TimeStamp]
FROM [dbo].[Customers] AS [t1]
WHERE ((@@ROWCOUNT) > 0) AND ([t1].[CustomerKey] = @p3)',

N'@p0 int,
@p1 timestamp,
@p2 varchar(40),
@p3 int',
@p2='Acme Widgets, LLC',

Notice how only the CustomerName column is updated instead of every column. This is one of the largest advantages over stored procs. Ordinarily, you'd probably write one stored proc to update the table and it would update every column. You definitely wouldn't want to write an SP for *every* column or permutation of columns.
Instead, what's produced is a nice tight query that only changes those columns that need to be changed. IMHO, this outweighs any perceived performance issues versus stored procs.

Technorati Tags: ,