I’m using fluent nhibernate for the first time to phase out my existing database access layer for accessing a remote MySql server.
The clients are mostly virtualized and can go to sleep/hibernate at any point in time, for any length of time (seconds to days). Even though they are usually time synchronous with the server that cannot be guaranteed, which means I cannot use the client provided DateTime for some fields.
How do I get nhibernate to set/update certain fields with the server time (preferably by calling the UTC_TIMESTAMP() function)?
Object:
public class MyObject{
public virtual UInt64 Id { get; set; }
public virtual String Status{ get; set; }
public virtual String SomeData{ get; set; }
//Set only once when the Object is inserted
public virtual DateTime TimeCreated { get; set; }
//Set every time the object is updated
public virtual DateTime TimeLastUpdate { get; set; }
//Set every time the 'Status' column is updated
public virtual DateTime TimeStatusLastChanged { get; set; }
//This is a user provides standard datetime field
public virtual DateTime SomeUserSpecifiedTime { get; set; }
}
Mapping:
Id(x => x.Id)
.GeneratedBy.Native();
Map(x => x.Status);
Map(x => x.SomeData);
Map(x => x.SomeUserSpecifiedTime);
//? -->
Map(x => x.TimeCreated)
.Not.Update();
Map(x => x.TimeLastUpdate);
Map(x => x.TimeStatusLastChanged);
//<-- ?
I want the three Time*-fields to use the UTC_TIMESTAMP() function, when they are set/updated, so the server side date/time gets inserted. The DateTime SomeUserSpecifiedTime field is a standard mapped field.
Until now my database access class contained the logic to create the queries in that way. I could create database triggers with the .Generated.Insert/Always mapping, but I was hoping there is a nhibernate/code-only way of doing that.
One solution I have found, is fetching the time from the server and providing it for the insert/update, but that is out, because the time between fetch and insert/update can be significant.
I’ve decided to solve the problem using triggers, which is not optimal, but works for now. Unfortunately nhibernate does not have a concept of triggers, so you have to declare them as auxiliary database objects, which leads to some problems
It might look something like this
In the configuration each trigger/aux. database object must be added individually:
The mapping
Custom user types or interceptors do not work unfortunately so it seems this is the only possible way to achieve this at the moment.