DateTime2 is driving me crazy

1.1k Views Asked by At

I'm using EF 4 (model First) in my project .NET and I having hard troubles with the DateTime fields.

When I'll use SaveChanges() this exception is thrown:

System.Data.SqlClient.SqlException : The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

I tried to use:

System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");

but nothing new happens. I'll explode my computer if I don't fix it this night.

I need help, I don't want explode my computer =( 1 week trying solve it without success

Here is my code:

protected void btnSave_Click(object sender, EventArgs e)
{
        int id = Convert.ToInt32(Request.QueryString["id"]);
        ModeloContainer ctx = new ModeloContainer();
        Cliente cli = ctx.Cliente.Where( cl => cl.IdCliente == id).First();
        Contrato c = new Contrato();

        c.Descricao = this.txtDescricao.Text;
        c.FaturarPara = this.ddlFaturarPara.SelectedValue;
        c.Tolerancia =  Convert.ToInt32(this.txtSuspenderContratoEm.Text);
        c.PeriodoPagto = this.ddlPeriodoPagamento.SelectedValue;

       // DateTime dtExpiracao = this.txtExpiraEm.Text.Trim() == "" ?                                                                       Convert.ToDateTime("01/01/0001") : Convert.ToDateTime(this.txtExpiraEm.Text.Trim());
        DateTime dt = DateTime.Now;
        System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");
        dt = Convert.ToDateTime(dt, enGB);

        c.ExpiraEm = dt; //Here is the problem! but I no have idea how fix it

        ctx.AddToContrato(c);
        ctx.SaveChanges();
        this.SalvarServiços(c.IdContrato);
}

I know, there's so many questions like this here, but none of them solves my problem.

I want insert date like this in TextBox: 09/08/2012

1

There are 1 best solutions below

0
On

I don't think there's any problem with your ExpiraEm column.

What I suspect is that you have another (or more than 1) datetime field which is non-nullable, and since you're not providing any value for them, EF will pass 01/01/0001 for them, which is not acceptable by SQL server (SQL Server's minimum acceptable date is January 1, 1753). So you get this SQL Exception.

Similar situations have been encountered here and here.