0

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

2
  • Try this post if that doesn't help you, can you post your model/
    – Mark Oreta
    Aug 9, 2012 at 20:51
  • 3
    Is there any other non-nullable DateTime field in your entity? If yes, it is source of your problem because EF is sending 1/1/0001 to that column. You can also use SQL profiler to check what values is EF trying to save to database. Aug 9, 2012 at 21:35

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.