efcore icon indicating copy to clipboard operation
efcore copied to clipboard

DateTime.Kind comes back as Unspecified

Open gzak opened this issue 10 years ago • 97 comments

If you store a DateTime object to the DB with a DateTimeKind of either Utc or Local, when you read that record back from the DB you'll get a DateTime object whose kind is Unspecified. Basically, it appears the Kind property isn't persisted. This means that a test to compare equality of the before/after value of a round trip to the DB will fail.

Is there something that needs to be configured for the Kind to be preserved? Or what's the recommended way to handle this?

gzak avatar Mar 07 '16 18:03 gzak

var entity = db.Entity.Single(e => e.Id == 123);
var now = DateTime.UtcNow;
entity.Date = now;
db.SaveChanges();

entity = db.Entity.Single(e => e.Id == 123);
Assert.Equal(now, entity.Date); // fails the assert

gzak avatar Mar 07 '16 20:03 gzak

A slight variation of this is that it would be nice if one could configure the default DateTimeKind. For example, I know that all dates in my database are Utc, so it would be nice if this was specified for all fetched dates in the DbContext, or maybe configurable per entity property?

rmja avatar Mar 08 '16 19:03 rmja

+1 on whar @rmja suggested, it's a really nice addition.

ilmax avatar Mar 09 '16 16:03 ilmax

One thing worth noting is that I think the DateTime type in C♯ has more precision than the DB equivalent, so equality probably won't be preserved after a round trip even with this change.

gzak avatar Mar 09 '16 23:03 gzak

Note for triage: Investigated mapping to DateTime CLR type to SQL Server datetimeoffset by default, but even when switching to the typed value buffer factory this still won't work without type conversions.

ajcvickers avatar Mar 23 '16 17:03 ajcvickers

Conclusions from triage:

  • This is fundamentally a limitation of SQL Server/SQL Client, where the kind of datetime is not persisted.
  • We could work around this by introducing a separate property to persist kind... but there is already DateTimeOffset which is designed to specifically store date/time in a time zone aware way. So really the solution isn't to try and workaround the limitations of DateTime, but educate folks to use DateTimeOffset.

rowanmiller avatar Mar 25 '16 17:03 rowanmiller

@rowanmiller how about my suggestion? It would be really useful in systems where the kind does not need to be stored, because it is agreed upon by convention.

rmja avatar Mar 25 '16 18:03 rmja

@rmja I should have mentioned that too... at the moment we rely on ADO.NET to construct the value and then we set it on the property. We do want to introduce a feature where you can control how that value is get/set from/to the property. This would allow things like setting DateTime.Kind, type conversions, using Get/Set methods rather than properties, etc. https://github.com/aspnet/EntityFramework/issues/240 is the issue tracking this feature

rowanmiller avatar Mar 25 '16 20:03 rowanmiller

@rowanmiller would you mind giving an example (like my second comment) that uses DateTimeOffset to correct the issue? Also, what type should I use for the corresponding column in the DB (assuming MSSQL server)?

gzak avatar Apr 22 '16 00:04 gzak

Never mind my last comment, I didn't realize there was a corresponding sql type called datetimeoffset. Basically, we've switched everything over to the -offset variants in both C# and the DB which solved this issue as well as #5175.

gzak avatar Apr 26 '16 20:04 gzak

@gzak glad it's working for you now

rowanmiller avatar Apr 26 '16 21:04 rowanmiller

I also would want such a convention @rmja mentioned (https://github.com/aspnet/EntityFramework/issues/4711#issuecomment-201405020). Because not all database providers have datetimeoffset type.

hikalkan avatar Apr 13 '17 14:04 hikalkan

I found a solution for that and shared as a blog post: http://volosoft.com/datetime-specifykind-in-entity-framework-core-while-querying/

hikalkan avatar Apr 19 '17 11:04 hikalkan

I had this same issue today. Why is Datetime/Timezones still an issue? I don't really care how DateTime is stored in the database as long as the returned value is the same as when I stored it. It could even be stored as a standardized(ISO 8601) string for all I care.

havheg avatar May 28 '17 16:05 havheg

Switching to DateTimeOffset doesn't solve the problem. It isn't time zone aware; it only stores the UTC offset for a specific instant in time. There is no simple way to derive the time zone where the value was created. Picking the underlying UTC value out of the DateTimeOffset value would be the best you could do and DateTime is just as good at assuming that.

EEaglehouse avatar Nov 28 '17 17:11 EEaglehouse

@EEaglehouse and others. I'm working on a change that will allow the kind to be be preserved by storing the DateTime as a long in the database and automatically converting it on the way in and out. Should be in 2.1 as part of #242.

ajcvickers avatar Nov 28 '17 17:11 ajcvickers

@ajcvickers Thank you. It would be nice to have that as an option. For me, the better solution remains to have an option to force the Kind to a particular value (Utc in my case) for DateTime values. Reading it as a DateTimeOffset is useless to me because I would still need to convert to DateTime with Kind as Utc in my applications' data layer; all local time zone conversions are handled in the presentation layer. Converting DateTime to a long for storage may be useful, but would effectively obfuscate the column type in the database. But please don't take this as discouraging you from implementing the custom type mapping, because then I could do for myself what I'm asking.

EEaglehouse avatar Nov 28 '17 19:11 EEaglehouse

@EEaglehouse Yes, after #242 you will be able to set things up to still store as a datetime in the database, but force a specific kind whenever it is read from the database.

ajcvickers avatar Nov 28 '17 19:11 ajcvickers

We are using this updated workaround from: http://volosoft.com/datetime-specifykind-in-entity-framework-core-while-querying/ Thank you @hikalkan, but I've made few changes, after few hours of debugging EF:

    public class DateTimeKindMapper
    {
        public static DateTime Normalize(DateTime value)
            => DateTime.SpecifyKind(value, DateTimeKind.Utc);

        public static DateTime? NormalizeNullable(DateTime? value)
            => value.HasValue ? DateTime.SpecifyKind(value.Value, DateTimeKind.Utc) : (DateTime?)null;

        public static object NormalizeObject(object value)
            => value is DateTime dateTime ? Normalize(dateTime) : value;
    }

    public class DateTimeKindEntityMaterializerSource : EntityMaterializerSource
    {
        private static readonly MethodInfo _normalizeMethod =
            typeof(DateTimeKindMapper).GetTypeInfo().GetMethod(nameof(DateTimeKindMapper.Normalize));

        private static readonly MethodInfo _normalizeNullableMethod =
            typeof(DateTimeKindMapper).GetTypeInfo().GetMethod(nameof(DateTimeKindMapper.NormalizeNullable));

        private static readonly MethodInfo _normalizeObjectMethod =
            typeof(DateTimeKindMapper).GetTypeInfo().GetMethod(nameof(DateTimeKindMapper.NormalizeObject));

        public override Expression CreateReadValueExpression(Expression valueBuffer, Type type, int index, IProperty property = null)
        {
            if (type == typeof(DateTime))
            {
                return Expression.Call(
                    _normalizeMethod,
                    base.CreateReadValueExpression(valueBuffer, type, index, property));
            }

            if (type == typeof(DateTime?))
            {
                return Expression.Call(
                    _normalizeNullableMethod,
                    base.CreateReadValueExpression(valueBuffer, type, index, property));
            }

            return base.CreateReadValueExpression(valueBuffer, type, index, property);
        }

        public override Expression CreateReadValueCallExpression(Expression valueBuffer, int index)
        {
            var readValueCallExpression = base.CreateReadValueCallExpression(valueBuffer, index);
            if (readValueCallExpression.Type == typeof(DateTime))
            {
                return Expression.Call(
                    _normalizeMethod,
                    readValueCallExpression);
            }

            if (readValueCallExpression.Type == typeof(DateTime?))
            {
                return Expression.Call(
                    _normalizeNullableMethod,
                    readValueCallExpression);
            }

            if (readValueCallExpression.Type == typeof(object))
            {
                return Expression.Call(
                    _normalizeObjectMethod,
                    readValueCallExpression);
            }

            return readValueCallExpression;
        }
    }

Workaround from @hikalkan works, except cases in subquery, like:

context.Entity.Select(e => new
{
    DateTimeField = e.NavigationProperty.OrderBy(n => n.OrderField).FirstOrDefault().DateTimeField
});

So extended EntityMaterializerSource can handle this as well, but because it wraps every object response as well, it can cause additional performance cost because of object to DateTime cast.

And it has additional fix for nullable DateTime as well. Before 2.1 we will use this workaround.

werwolfby avatar Jan 18 '18 06:01 werwolfby

Hi, Alexander,

That looks like a nice solution and more advanced than the solution we have been using, which was to use T4 to generate a custom DBContext. The code you presented is pretty easy to understand and not very complicated. When we migrate to .NET Core, this will definitely come in handy.

Thank you very much for taking the time to share it with me!

--Ed

From: Alexander Puzynia [mailto:[email protected]] Sent: Thursday, January 18, 2018 1:32 AM To: aspnet/EntityFrameworkCore [email protected] Cc: Ed Eaglehouse [email protected]; Mention [email protected] Subject: Re: [aspnet/EntityFrameworkCore] DateTime.Kind comes back as Unspecified (#4711)

We are using this updated workaround from: http://volosoft.com/datetime-specifykind-in-entity-framework-core-while-querying/

public class DateTimeKindMapper

{

    public static DateTime Normalize(DateTime value)

        => DateTime.SpecifyKind(value, DateTimeKind.Utc);



    public static DateTime? NormalizeNullable(DateTime? value)

        => value.HasValue ? DateTime.SpecifyKind(value.Value, DateTimeKind.Utc) : (DateTime?)null;



    public static object NormalizeObject(object value)

        => value is DateTime dateTime ? Normalize(dateTime) : value;

}



public class DateTimeKindEntityMaterializerSource : EntityMaterializerSource

{

    private static readonly MethodInfo _normalizeMethod =

        typeof(DateTimeKindMapper).GetTypeInfo().GetMethod(nameof(DateTimeKindMapper.Normalize));



    private static readonly MethodInfo _normalizeNullableMethod =

        typeof(DateTimeKindMapper).GetTypeInfo().GetMethod(nameof(DateTimeKindMapper.NormalizeNullable));



    private static readonly MethodInfo _normalizeObjectMethod =

        typeof(DateTimeKindMapper).GetTypeInfo().GetMethod(nameof(DateTimeKindMapper.NormalizeObject));



    public override Expression CreateReadValueExpression(Expression valueBuffer, Type type, int index, IProperty property = null)

    {

        if (type == typeof(DateTime))

        {

            return Expression.Call(

                _normalizeMethod,

                base.CreateReadValueExpression(valueBuffer, type, index, property));

        }



        if (type == typeof(DateTime?))

        {

            return Expression.Call(

                _normalizeNullableMethod,

                base.CreateReadValueExpression(valueBuffer, type, index, property));

        }



        return base.CreateReadValueExpression(valueBuffer, type, index, property);

    }



    public override Expression CreateReadValueCallExpression(Expression valueBuffer, int index)

    {

        var readValueCallExpression = base.CreateReadValueCallExpression(valueBuffer, index);

        if (readValueCallExpression.Type == typeof(DateTime))

        {

            return Expression.Call(

                _normalizeMethod,

                readValueCallExpression);

        }



        if (readValueCallExpression.Type == typeof(DateTime?))

        {

            return Expression.Call(

                _normalizeNullableMethod,

                readValueCallExpression);

        }



        if (readValueCallExpression.Type == typeof(object))

        {

            return Expression.Call(

                _normalizeObjectMethod,

                readValueCallExpression);

        }



        return readValueCallExpression;

    }

}

Workaround from volosoft works, except cases in subquery, like:

context.Entity.Select(e => new

{

DateTimeField = e.NavigationProperty.OrderBy(n => n.OrderField).FirstOrDefault().DateTimeField

});

So extended EntityMaterializerSource can handle this as well, but because it wraps every object response as well, it can cause additional performance cost because of object to DateTime cast.

And it has additional fix for nullable DateTime as well. Before 2.1 we will use this workaround.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://github.com/aspnet/EntityFrameworkCore/issues/4711#issuecomment-358551156, or mute the threadhttps://github.com/notifications/unsubscribe-auth/ASrwvT9VrPRI9gyXit0b6RQOJd0K7-zyks5tLuVMgaJpZM4HrCRe.

EEaglehouse avatar Jan 18 '18 14:01 EEaglehouse