Search code examples
c#sql-serverdapper

DateTime Parameters in stored procedure


I have a stored procedure insert into to the table in SQL Server:

CREATE PROCEDURE ThemHocSinh
    @TenHS NVARCHAR(255),
    @NgaySinh DATETIME,
    @TenChaMe NVARCHAR(255),
    @SDTChaMe VARCHAR(16),
    @DiaChi NVARCHAR(255),
    @LopHC VARCHAR(6)
AS
    INSERT INTO dbo.HocSinh (MaHS, TenHS, NgaySinh, NgayNhapHoc, TenChaMe, SDTChaMe, DiaChi, LopHC)
    VALUES (DEFAULT, @TenHS, @NgaySinh, DEFAULT, @TenChaMe, @SDTChaMe, @DiaChi, @LopHC)

I write a function in C# with Dapper and passing the dynamic parameters with DateTime type.

public void ThemHocSinh(string TenHS, DateTime NgaySinh, string TenChaMe, string SDT, string DiaChi, string LopHC)
{
    using (MamNonBK context = new MamNonBK())
    {
        using (IDbConnection db = new SqlConnection(context.Database.Connection.ConnectionString))
        {
            var p = new DynamicParameters(); 
            p.Add("@TenHS", TenHS);
            p.Add("@NgaySinh", NgaySinh); 
            p.Add("@TenChaMe", TenChaMe); 
            p.Add("@SDTChaMe", SDT); 
            p.Add("@DiaChi", DiaChi);
            p.Add("@LopHC", LopHC);

            db.Execute("ThemHocSinh", p, commandType: CommandType.StoredProcedure);
        }
    }
}

But it seems my program crashes because the dateTime parameter does not match. My system date and time is formatted "dd/MM/yyyy". This is error when I call the function and pass a DateTime parameter.

System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

enter image description here


Solution

  • Since SQL receives a string not formatted the way it wants, you can also use:

    p.Add("@NgaySinh", NgaySinh.ToString("yyyy-MM-dd"));

    instead of:

    p.Add("@NgaySinh", NgaySinh);

    and I'm sure it'll work!