Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

.NET 6 DateOnly and TimeOnly mapping support

Open arnederuwe opened this issue 4 years ago • 17 comments

.NET 6 will introduce the DateOnly and TimeOnly structs, these are good mapping candidates for SQL Server's Date and Time types.

There is an open issue in the .NET SqlClient repo here

Am I correct to assume that once SqlClient supports it, Dapper will implicitly support it as well? Or is there some work required in this repo as well in order for this to work?

arnederuwe avatar Oct 07 '21 13:10 arnederuwe

I gave this a try with an Npgsql 6.0 RC, which does already support DateOnly/TimeOnly, and it seems this doesn't work:

await conn.ExecuteScalarAsync("SELECT @Foo", new { Foo = new DateOnly(2020, 1, 1) })

Throws:

Unhandled exception. System.NotSupportedException: The member Foo of type System.DateOnly cannot be used as a parameter value
   at Dapper.SqlMapper.LookupDbType(Type type, String name, Boolean demand, ITypeHandler& handler) in /_/Dapper/SqlMapper.cs:line 417
   at Dapper.SqlMapper.CreateParamInfoGenerator(Identity identity, Boolean checkForDuplicates, Boolean removeUnused, IList`1 literals) in /_/Dapper/SqlMapper.cs:line 2504
   at Dapper.SqlMapper.GetCacheInfo(Identity identity, Object exampleParameters, Boolean addToCache) in /_/Dapper/SqlMapper.cs:line 1727
   at Dapper.SqlMapper.ExecuteScalarImplAsync[T](IDbConnection cnn, CommandDefinition command) in /_/Dapper/SqlMapper.Async.cs:line 1200
   at Program.<Main>$(String[] args) in /home/roji/projects/test/Program.cs:line 12
   at Program.<Main>$(String[] args) in /home/roji/projects/test/Program.cs:line 12
   at Program.<Main>(String[] args)

Somewhat related to #1716... I know nothing about Dapper internals, but ideally it would be possible to use any arbitrary .NET type as a parameter, and Dapper would simply pass that along to the DbParameter.Value, without anything else (that would obviate needing any special type handlers or something). But there may be some good reason why things don't work this way currently.

roji avatar Oct 18 '21 10:10 roji

I tracked the source code and found that the TimeOnly and DateOnly types are not supported here. I am not sure if adding these two types to the collection and specifying them as DbType.Date and DbType.Time will work. I will try if it works.

Dapper does not support .NET 6, so DateOnly and TimeOnly types cannot be used

Reference: System.Data.DbType

FatTigerWang avatar Oct 19 '21 08:10 FatTigerWang

Any timeline when this may be fixed?

kevingates avatar Dec 09 '21 15:12 kevingates

@kevingates see also #1728; there is an open branch, but we need to first be sure how this is intended to interact with the various providers

mgravell avatar Dec 09 '21 19:12 mgravell

Very much would like to see this. It is weird that SQL Server's DATE type should map to anything but DateOnly in C#.

szalapski avatar Apr 01 '22 19:04 szalapski

For those who are looking for a workaround: make your own type handler.

Add the following to your configuration:

SqlMapper.AddTypeHandler(new SqlTimeOnlyTypeHandler());

public class SqlTimeOnlyTypeHandler : SqlMapper.TypeHandler<TimeOnly>
{
    public override void SetValue(IDbDataParameter parameter, TimeOnly time)
    {
        parameter.Value = time.ToString();
    }

    public override TimeOnly Parse(object value)
    {
        return TimeOnly.FromTimeSpan((TimeSpan)value);
    }
}

h181422 avatar Jun 03 '22 16:06 h181422

And similarly for DateOnly:

public class DapperSqlDateOnlyTypeHandler : SqlMapper.TypeHandler<DateOnly>
{
    public override void SetValue(IDbDataParameter parameter, DateOnly date)
        => parameter.Value = date.ToDateTime(new TimeOnly(0, 0));
    
    public override DateOnly Parse(object value)
        => DateOnly.FromDateTime((DateTime)value);
}

danielearwicker avatar Jun 08 '22 09:06 danielearwicker

I had problems with database conversion so I had to specify the type. Like this

public override void SetValue(IDbDataParameter parameter, DateOnly date)
{
    parameter.DbType = DbType.DateTime;
    parameter.Value = date.ToDateTime(new TimeOnly(0, 0));
}

K0rhak avatar Jun 17 '22 11:06 K0rhak

How exactly is the TypeHandler used? I have the following line in the constructor of my DB class

SqlMapper.AddTypeHandler(new DateOnlyTypeHandler());
SqlMapper.AddTypeHandler(new TimeOnlyTypeHandler());

and the following TypeHandlers

public class DateOnlyTypeHandler : SqlMapper.TypeHandler<DateOnly>
{
    public override DateOnly Parse(object value) => DateOnly.FromDateTime((DateTime)value);

    public override void SetValue(IDbDataParameter parameter, DateOnly value)
    {
        parameter.DbType = DbType.Date;
        parameter.Value = value;
    }
}

public class TimeOnlyTypeHandler : SqlMapper.TypeHandler<TimeOnly>
{
    public override TimeOnly Parse(object value) => TimeOnly.FromDateTime((DateTime)value);

    public override void SetValue(IDbDataParameter parameter, TimeOnly value)
    {
        parameter.DbType = DbType.Time;
        parameter.Value = value;
    }
}

But I'm still getting a an exception that the Date field in my object is NULL and the breakpoints on the convertion methods aren't being hit.

PedroC88 avatar Jul 08 '22 22:07 PedroC88

SqlMapper.AddTypeHandler(new DateOnlyTypeHandler());
SqlMapper.AddTypeHandler(new TimeOnlyTypeHandler());

I've got them in my container config, where they are registered at startup.

h181422 avatar Jul 08 '22 23:07 h181422

That makes more sense indeed. And I also realized that z.dapper.pluss doesn't use the TypeHandlers for bulk inserts, which is why the breakpoints weren't hitting the methods in the first place.

PedroC88 avatar Jul 11 '22 14:07 PedroC88

Found this issue in a search and was able to get the type handlers working (The SqlMapper.AddTypeHandler lines go in Startup.cs \ ConfigureServices if you're working on an API by they way, that took me a few minutes to figure out).

However, to make them work in converting either a MS SQL DateTime OR a MS SQL Time to TimeOnly, I needed this modification (MS SQL Date to DateOnly seemed to work without change):

    public class DateOnlyTypeHandler : SqlMapper.TypeHandler<DateOnly> // Dapper handler for DateOnly
    {
        public override DateOnly Parse(object value) => DateOnly.FromDateTime((DateTime)value);

        public override void SetValue(IDbDataParameter parameter, DateOnly value)
        {
            parameter.DbType = DbType.Date;
            parameter.Value = value;
        }
    }

    public class TimeOnlyTypeHandler : SqlMapper.TypeHandler<TimeOnly> // Dapper handler for TimeOnly
    {
        public override TimeOnly Parse(object value)
        {
            if (value.GetType() == typeof(DateTime))
            {
                return TimeOnly.FromDateTime((DateTime)value);
            }
            else if (value.GetType() == typeof(TimeSpan))
            {
                return TimeOnly.FromTimeSpan((TimeSpan)value);
            }
            return default;
        }

        public override void SetValue(IDbDataParameter parameter, TimeOnly value)
        {
            parameter.DbType = DbType.Time;
            parameter.Value = value;
        }
    }

Hopefully these mappings can be added to default dapper one day

ScottRFrost avatar Mar 21 '23 15:03 ScottRFrost

Make sure to declare the DateOnly property is declared as Nullable DateOnly? if the table contains a null values

yacine-karim avatar May 10 '23 17:05 yacine-karim

SetValue function is called and it works, however Parse is never called. It's always returning NULL

AdisonCavani avatar May 19 '23 16:05 AdisonCavani

Is there still no native support for DateOnly & TimeOnly?

nhustak avatar Sep 17 '23 20:09 nhustak

There are some complications on the read side that make it a much bigger change than you would think. I have some ideas,though.

mgravell avatar Sep 17 '23 22:09 mgravell

To make this work with record classes I've been using an alternative constructor, which may be useful to others working around this...

With a select like:

select convert(date, Created) 'day', count(*) 'value' 
from...
group by convert(date, Created)

This crashes:

public record WithDateOnly(DateOnly Day, int Value);

Because there is no constructor accepting System.DateTime, System.Int32, even though SQL has output its native date type.

The workaround is to add an alternative constructor:

public record WithDateOnly(DateOnly Day, int Value) {
    public WithDateOnly(DateTime day, int value) : 
        this(DateOnly.FromDateTime(day), value) { }
}

KeithHenry avatar Oct 17 '23 09:10 KeithHenry

Just hit this today. Would love to see this built-in. DateOnly has been in 2 major .NET versions now.

VictorioBerra avatar Mar 06 '24 19:03 VictorioBerra

Untested (not at PC), but you could try:

SqlMapper.AddTypeMap(typeof(DateOnly), (DbType)-1, true);
SqlMapper.AddTypeMap(typeof(TimeOnly), (DbType)-1, true);

It is hard for us to configure this automatically because different providers need different configurations to work correctly here.

mgravell avatar Mar 06 '24 21:03 mgravell

After dependencies upgrade to latest versions, new .NET types seem to work fine with Dapper.

<ItemGroup>
  <PackageReference Include="Dapper" Version="2.1.37" />
  <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
</ItemGroup>

And custom type handlers SqlMapper.TypeHandler<DateOnly> are not used by Dapper any more.

mkorsukov avatar Mar 21 '24 15:03 mkorsukov