Skip to content

DateOnly Output SqlParameter #2092

@brandonryan

Description

@brandonryan

Problem

The new DateOnly CLR type maps nicely to the SQL date for input parameters now, but there is no way for me to tell the sql driver that I want sql date output parameters to be DateOnly. (Potentially the same with TimeOnly instead of time span).

Example

Exec Stored Procedure

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace Brandon.Expirements
{
    public class Program
    {
        private const string ExecProcCmd = "EXEC test.DateOnlyOutputParam @in, @out OUTPUT";

        public static void Main()
        {
            var ctx = new ExpContext();

            var inParam = new SqlParameter("@in", new DateOnly(1996, 06, 27));
            var outParam = new SqlParameter()
            {
                ParameterName = "@out",
                Direction = System.Data.ParameterDirection.InputOutput,
                DbType = System.Data.DbType.Date,
            };

            ctx.Database.ExecuteSqlRaw(ExecProcCmd, inParam, outParam);

            Console.WriteLine(outParam.Value.GetType().Name); //Logs: DateTime
        }
    }
}

Stored Procedure

CREATE PROC [test].[DateOnlyOutputParam] (
    @in Date, 
    @out Date OUTPUT
)
AS
BEGIN
    SET @out = @in;
END;

Proposed Solution

It would be nice if there was some kind of configuration flag, or custom converter interface, but I'm not sure where you would put it.
An alternative solution could be using the Value parameter as a hint of what type is expected out. This feels a bit like magic behavior though, more meant as a last resort if configuration isn't an option.

var outParam = new SqlParameter()
{
    ParameterName = "@out",
    Direction = System.Data.ParameterDirection.InputOutput,
    DbType = System.Data.DbType.Date,
    Value = DateOnly.MaxValue, //hints to driver that we want a DateOnly Value
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions