Patrick Szalapski
Patrick Szalapski

Reputation: 9439

How can I avoid setting some columns if others haven't changed, when working with Linq To SQL?

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?

Upvotes: 1

Views: 62

Answers (2)

msarchet
msarchet

Reputation: 15242

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

Upvotes: 1

Agent_9191
Agent_9191

Reputation: 7253

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.

Upvotes: 0

Related Questions