Synchronizing AutoGenerated Properties After SubmitChanges
When you insert or update a record in the database, there are certain columns whose values are either generated because they are identity columns, or columns whose value is assigned by SQL server such as timestamp column. You could have triggers that update columns after an insert or update on the table. Those column values are not reflected in your entity. However linq to SQL offers different syncing options to sync properties on your entities with column values generated by the database. You can use AutoSync parameter on your columns and specify when linq to SQL should update those columns such as OnInsert, OnUpdate,Always,Default and Never. I have generated a sample class that show variety of syncing options that you can apply on your properties to sync your entities after insert and update of a record to the database.
Let's start with OrderId column. Since OrderId is defined as AutoGenerated key I am setting IsDbGenerated to true. Since the column value is going to be generated by the database, I need to tell linq to SQL to AutoSync the column. Therefore I am setting AutoSync.Default. The Default option means that if the column is marked with IsDbGenerated than update the column on the insert of an entity. If the column is IsVersion column like I have a timestamp column, than update the column on insert or update operation.
The Actual Column in our database is a calculated column that is obtained by multiplying DiscountPer and OrderTotal and dividing the results by 100 . I am setting the sync option to be always meaning always update the value of this column from what's in the database.
Since CreateDate is only assigned first time record is inserted, I am setting the AutoSync to Insert, to update the column only when the entity gets inserted.
Since Modified date is only set when the entity gets modified,I am setting the AutoSync to OnUpdate, to update the column only when entity gets updated.
Below is an example of inserting an instance of Order entity and than updating the entity to confirm that our auto sync parameters update our respected properties.
In the above code, after inserting the order entity in the database, I am printing the OrderId,Actual,CreateDate and ModifiedDate on the output screen. Notice on the insert our modified date is set to null because we have configured the column to be synced up when the entity gets modified. After printing the output, I update the DiscountPer column and send the changes to the database by calling SubmitChanges. This time our modified column reflects the correct value for ModifiedDate.