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?
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
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.
精彩评论