Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Nhibernate - configure all dates to be rehydrated from UTC

This SO question talks about "Rehydrating fluent nhibernate configured DateTime as Kind Utc rather than Unspecified".

One of the later answers in that question has this:

Map(x => x.EntryDate).CustomType<UtcDateTimeType>();

That works for one property on one entity.

I would like to know if there is a way to specify that ALL datetime properties are stored as UTC in the database.

Is this possible, and if so, how?

like image 898
richard Avatar asked Mar 09 '15 04:03

richard


2 Answers

The way with fluent NHibernate is Convention

Conventions

James Gregory edited this page on 3 Apr 2012 · 1 revision

...
The conventions are built using a set of interfaces and base classes that each define a single method, Apply, with varying parameters based on the kind of convention you're creating; this method is where you make the changes to the mappings.
...

Drafted example:

public class UtcConvention : IPropertyConvention
{
    public void Apply(IPropertyInstance instance)
    {
        if (instance.Type.Name == "Date")
        {
            instance.CustomType<UtcDateTimeType>();
        }
    }
}

We have to add this into configuration

FluentMappings
  .Conventions.Add(new UtcConvention())
like image 50
Radim Köhler Avatar answered Nov 03 '22 01:11

Radim Köhler


Hi Thanks for the answer Radim,

I have to make some minor changes to you code to get it to work and support nullable DateTime? properties.

    public class UtcConvention : IPropertyConvention  {
        public void Apply(IPropertyInstance instance) {
            if (instance.Type.Name == "DateTime" || instance.Type.ToString().StartsWith("System.Nullable`1[[System.DateTime")) {
                instance.CustomType<UtcDateTimeType>();
            }
        }
    }

Maybe this might help someone else looking for a solution

like image 29
Dai Bok Avatar answered Nov 02 '22 23:11

Dai Bok