SQL Server TimeOnly data type is not supported in Dapper in C# .NET6 API project

4si2a6ki  于 2022-12-22  发布在  C#
关注(0)|答案(2)|浏览(176)

I am using Dapper in an ASP.NET Core 6 Web API project with SQL Server 2016 database as backend. The ExecuteScalar method of Dapper is returning an error
The member DepartureTime of type System.TimeOnly cannot be used as a parameter value
Is there any workaround?

public virtual int Create(TModel entity)
{
    int result = -1;
    var insertQuery = QueryGenerator.GenerateInsertQuery(typeof(TModel));
    var factory = new SqlServerDbConnectionFactory(connectionString);
    var profiler = CustomDbProfiler.Current;

    using (var connection = ProfiledDbConnectionFactory.New(factory, profiler))
    {
        try
        {
            if (connection.State == ConnectionState.Closed)
            {
                connection.ConnectionString = connectionString;
                connection.Open();
            }

            result =  connection.ExecuteScalar<int>(insertQuery, entity, transaction: null); // Throwing error
        }
        catch (Exception e)
        {
            var sql = profiler.GetCommands();
            throw;
        }
    }

    return result;
}

insertQuery contains the following query:

INSERT INTO [Flight] ([FlightNumber], [SourceCode], [DestinCode],[DepartureTime], [EffectDate], [Stops], [TravelMinutes]) 
VALUES (@FlightNumber, @SourceCode, @DestinCode, @DepartureTime, @EffectDate, @Stops, @TravelMinutes);
SELECT SCOPE_IDENTITY()

entity is of type FlightModel :

public class FlightModel
{
    public int Id { get; set; }
    public string FlightNumber{ get; set; }
    public string SourceCode{ get; set; }
    public string DestinCode { get; set; }
    public TimeOnly DepartureTime{ get; set; }
    public DateOnly EffectDate { get; set; }
    public int Stops{ get; set; }
    public int TravelMinutes { get; set; }
}
vdzxcuhz

vdzxcuhz1#

From here, 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);
    }
}
6ljaweal

6ljaweal2#

您可以使用TimeSpan

public class FlightModel
{
    ...
    public TimeSpan DepartureTime{ get; set; }
    public DateTime EffectDate { get; set; }
}

相关问题