Question

I'm using S#arpArchitecture (ASP.NET MVC and Fluent NHibernate). I have an entity as follows:

public class User : Entity
{
    public User(){}
    public User(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual DateTime? LastUpdate{ get; set; }
}

I will call the SaveOrUpdate method on my repository class that will persist this User object. It works. How would i persist the LastUpdate property automatically with the latest date and time? I could override the SaveOrUpdate method in my repository by always setting the LastUpdate property to the current date and time but that does not seem to be correct because if there's nothing changed in my entity, I don't think NHibernate will persist my object back to the DB and forcing the setting of this property will always make it persist back.

I only want this LastUpdate property set if something else has changed in my entity.

Was it helpful?

Solution 3

I'm going to point to another StackOverflow question that I think answers my question.

OTHER TIPS

You should use an NHibernate Interceptor to accomplish this. Override OnFlushDirty in your interceptor implementation to set the LastUpdate property only when something has changed (i.e. your object is dirty).

Since you didn't specify your database type, I will take the liberty and add a solution for people using MySQL / MariaDB:

You can use the following in your fluent mapping class:

Map(y => y.LastUpdate).CustomSqlType("timestamp").Generated.Always();

This creates a MySQL TIMESTAMP column with a default value of CURRENT_TIMESTAMP. Thus, if Nhibernate chooses to flush your entity, MySQL will make sure that the column is properly updated.

I'm pretty sure this does not play well with MSSQL as TIMESTAMPS are different beasts in MSSQL (here and here)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top