簡體   English   中英

使用Nhibernate將C#DateTime映射到SQL Server datetimeoffset

[英]Mapping C# DateTime to SQL Server datetimeoffset using Nhibernate

假設您有一個相當復雜的系統,並且大量使用了DateTime(超過1k個位置,並且一些幫助程序和擴展名依賴於確切的類型)。 假設您決定從現在開始需要存儲UTC日期。

我最初的想法是用DateTimeOffset替換所有DateTime類型,但這並不是一件容易的事,因為它在不同上下文中的使用率很高。

問題是我是否可以僅更改NHiberante映射,而不必更改系統其余部分中使用的類型。 還是那么大的重構是唯一的方法?

如果您使用NHibernate Fluent Automapping,這是我的慣例:

    public class UtcDateTimeConvention : IPropertyConvention, IPropertyConventionAcceptance
    {
        public void Apply(IPropertyInstance instance)
        {
            instance.CustomType<UtcDateTimeType>();
        }

        public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
        {
            criteria.Expect(x =>
                x.Property.PropertyType.Equals(typeof(DateTime)) ||
                x.Property.PropertyType.Equals(typeof(DateTime?)));
        }
    }

我更喜歡保留UtcDateTimeType,而不是將其轉換為本地:

        public static DateTime ToUserTimeZone(this DateTime utcDateTime, TimeZoneInfo currentTimeZone)
        {
            if (utcDateTime.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("utcDateTime.Kind != DateTimeKind.Utc", "utcDateTime");
            }

            return TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, currentTimeZone);
        }

        public static DateTime? ToUserTimeZone(this DateTime? utcDateTime, TimeZoneInfo currentTimeZone)
        {
            if (utcDateTime.HasValue)
            {
                return ToUserTimeZone(utcDateTime.Value, currentTimeZone);
            }

            return null;
        }

如果數據庫始終存儲UTC值,則可以使用NHibernate UtcDateTime類型而不是常規DateTime類型映射DateTime字段。 有關示例,請參見http://codebetter.com/jameskovacs/2011/01/26/datetime-support-in-nhibernate/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM