views:

27

answers:

2

In LINQ to SQL, I want to avoid setting some columns if others haven't changed? Say I have

dim row = (From c in dataContext.Customers Where c.Id = 1234 Select c).Single()
row.Name = "Example"
' line 3
dataContext.SubmitChanges()   ' line 4

Great, so LINQ to SQL fetches a row, sets the name to "Example" in memory, and generates an update SQL query only when necessary--that is, no SQL will be generated if the customer's name was already "Example".

So suppose on line 3, I want to detect if row has changed, and if so, set row.UpdateDate = DateTime.Now. If row has not changed, I don't want to set row.UpdateDate so that no SQL is generated. Is there any good way to do this?

+1  A: 

You could implement something like this, as I'm not sure if there is a default way to accomplish this since you are setting the property.

Dim row = (From c in dataContext.Customers Where c.id = 1234 Select c).Single
if (row.Name <> "Example") Then
    row.Name = "Example"
    row.UpdateDate = DateTime.Now
End If
datacontext.SubmitChanges()

EDIT

There is a PropertyChanged Event inside of the datacontext class that you could hook into.

So you could do something like

AddHandler row.PropertyChanged, AddressOf UpdateRowDate

msarchet
That's what I was afraid of. You can imagine if there are ten columns to set, then I have to manage ten predicates in my conditional. I'm hoping for a way just to say [ If row.HasChanged() Then row.UpdateDate = DateTime.Now ]I could write my own method if I knew how to detect if row has changed in-memory.
Patrick Szalapski
made a edit after looking at a generated datacontext class
msarchet
You can use PropertyChanged, but it is also cumbersome.
Patrick Szalapski
A: 

I can't think of the actual code off the top of my head, but since Linq-to-SQL entities are partial classes just extend some logic into them to check for this. Every property has events on when they are changed, so in your partial class bind to the property changed event and have it set the UpdateDate on the object.

Agent_9191