Timestamps for Entity Tracking and Soft Deletion
By default, the times stored by LightSpeed for the CreatedOn, UpdatedOn and DeletedOn fields are the current local time of the computer where LightSpeed is running. You may want to override this. For example, if a database is shared across multiple time zones, you may want to use UTC or some other standard time zone so that the sort order is consistent regardless of which site created or updated a record. Or you may want to force a ‘fake’ time for unit testing purposes.
To do this, set LightSpeedContext.AutoTimestampMode in code, or the autoTimestampMode attribute in configuration. The available values are defined by the AutoTimestampMode enumeration.
Setting the timestamp strategy in configuration |
<add name="Test" |
Built-In Timestamp Strategies
There are two built-in timestamp strategies, Local and Utc.
· Local: The timestamp is the local time of the computer where LightSpeed is running.
· Utc: The timestamp is UTC/GMT.
In both cases the time comes from the clock of the machine where LightSpeed is running. If clocks are not well synchronised then the errors will be reflected in the stored timestamps.
Using a Custom Timestamp Strategy
If you use the Custom mode, you must also implement IAutoTimestampStrategy, and set LightSpeedContext.CustomAutoTimestampStrategy to an instance of that implementation.
Implementing IAutoTimestampStrategy for unit testing |
public class FixedAutoTimestampStrategy : IAutoTimestampStrategy |
Using the custom strategy |
_context.AutoTimestampMode = AutoTimestampMode.Custom; |
You can also specify a custom timestamp strategy in configuration using its assembly‑qualified type name. In this case the strategy class cannot take constructor parameters.
Setting a custom timestamp strategy in configuration |
<add name="Test" |
Database-side Timestamping
LightSpeed 5 also includes support for database-side timestamps. With your custom timestamp strategy implementation, have it also implement the IAutoTimestampExpressionStrategy interface. Your GetTimeExpression() method should return the desired SQL expression for the column, or null to use the client-side timestamp returned from IAutoTimestampStrategy.GetTime(). Here’s one implementation:
Setting a custom timestamp strategy in configuration |
public object GetTimeExpression(Type type, TimestampUsage usage, LightSpeedContext context) { |
LightSpeed will not read back the timestamp generated by the database. After saving changes, therefore, the entity will contain the timestamp returned from IAutoTimestampStrategy.GetTime(). If your application needs to know the timestamp generated by the database, you will need to reload the entity.
If your application needs to be portable across different database engines, you can use the LightSpeedContext.DataProvider value to determine which database is being targeted.