‫مشکلات نوع داده DateTime در NHibernate

در NHibernate فیلدهایی که از نوع DateTime تعریف می‌شوند دارای مشکلاتی هستند. از جمله:

۱- اگر به جای DateTime?‎ (نوع nullable) از DateTime استفاده کنید، به خاطر این که SQL Server Min. DateTime با ‎.Net Min DateTime تفاوت دارد، آبجکت خود به خود dirty شده و احتمالاً یک update اضافه به سیستم تحمیل خواهد شد. ±

۲- DateTimeهایی که از طریق NHibernate ذخیره می‌شوند دقت پایین‌تری نسبت به SQL دارند. ±

۳- متفاوت بودن دقت NHibernate و SQL ممکن است باعث dirty شدن خود به خود آبجکت هم بشود. ±

Saving time as UTC with NHibernate

In many applications that have world wide users, there is a need to dealing with UTC. In these applications, time is stored in UTC and then showed backed in local time to users. A good solution is not to bother developers to convert time to universal or local time every time manipulating time related data. Instead we could add a bit of code to setter getter of DateTime fields. Unfortunately this solution does not work in NHibernate and possibly other ORMs. Consider following code:

DateTime _myDate;

[Property]
public virtual DateTime MyDate
{
    set { _myDate = value;}
    get {return _myDate;}
}

In this code we can not add a ToLocalTime() or ToUniversalTime() to setter or getter. Because both NHibernate and the application use this same getter and setter. Real solution is to use a helper field. This way the helper field will not persist on database but real field persists on database. Real field mus not be accessible to developer because of confusion and possible unwanted changes. Consider final solution:

public virtual DateTime MyDate //helper field
{
    set { MyDateUtc = value.ToUniversalTime(); }
    get { return MyDateUtc.ToLocalTime(); }
}

[Property]
private DateTime MyDateUtc { set; get; } //real field

All codes are based on Castle Active Record.