Error when trying to insert DateTime.MinValue into the database

2

I have an object that has a DateTime property, and I initialize it with the value of the DateTime.MinValue property

The problem is that passing this value to register in the SQL Server database gives an error:

  

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and   12/31/9999 11:59:59 PM

I understand that the error is because the MinValue property returns a value less than the minimum accepted by SQL Server, but has to make the MinValue value compatible with the database in use (in this case SQL Server) ?

Is there a better way to insert an empty date into the database?

    
asked by anonymous 10.05.2017 / 16:55

1 answer

3

You can simply pass%% of the bank as a parameter to when your variable has null . In the parameter, you must convert your date to MinValue to be compatible with Object .

See the code:

DateTime suaData = DateTime.MinValue;

using (SqlConnection conn = new SqlConnection(connectionString)) {
    try {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand()) {
            cmd.Connection = conn;

            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@data", suaData == DateTime.MinValue ? DBNull.Value : (object)suaData);
            cmd.CommandText = "insert into TBL_data values(@data)";
            cmd.ExecuteNonQuery();
        }
    }
    catch (Exception ex) {
        Console.WriteLine(ex.Message); //exibe no console o erro
    }
}

I created this table DBNull.Value as test, it has a field TBL_data only.

    
10.05.2017 / 17:13